0% found this document useful (0 votes)
24 views

Cybrom Python Notes

Python is a general purpose, high-level programming language created by Guido van Rossum in 1991. It is an interpreted language with object-oriented, imperative, and functional programming features. Python can be used for many types of applications including web development, data analysis, and game development. It is an open source and platform independent language with a large standard library and active development community.

Uploaded by

Aval Saxena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Cybrom Python Notes

Python is a general purpose, high-level programming language created by Guido van Rossum in 1991. It is an interpreted language with object-oriented, imperative, and functional programming features. Python can be used for many types of applications including web development, data analysis, and game development. It is an open source and platform independent language with a large standard library and active development community.

Uploaded by

Aval Saxena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Python

(Part-I)

1
Language Fundamentals

Introduction
 Python is a general purpose high level programming language.

 Python was developed by Guido Van Rossam in 1989 while working at National
Research Institute at Netherlands.

 But officially Python was made available to public in 1991. The official Date of Birth for
Python is : Feb 20th 1991.

 Python is recommended as first programming language for beginners.

The name Python was selected from the TV Show


"The Complete
Monty
Python's
Circus", which was broadcasted in BBC from 1969 to 1974.

Guido developed Python language by taking almost all programming features from
different languages

1. Functional Programming Features from C


2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4. Modular Programming Features from Modula-3

Most of syntax in Python Derived from C and ABC languages.

Where we can use Python:

We can use everywhere. The most common important application areas are

1. For developing Desktop Applications


2. For developing web Applications
3. For developing database Applications
4. For Network Programming
5. For developing games
6. For Data Analysis Applications
7. For Machine Learning
8. For developing Artificial Intelligence Applications
9. For IOT
...

Note:

Internally Google and Youtube use Python coding


NASA and Nework Stock Exchange Applications developed by Python.
Top Software companies like Google, Microsoft, IBM, Yahoo using Python.

Features of Python:
1. Simple and easy to learn:

Python is a simple programming language. When we read Python program,we can feel like
reading english statements.
The syntaxes are very simple and only 30+ kerywords are available.
When compared with other languages, we can write programs with very less number of
lines. Hence more readability and simplicity.
We can reduce development and cost of the project.

2. Freeware and Open Source:

We can use Python software without any licence and it is freeware.

Its source code is open,so that we can we can customize based on our requirement.

Eg: Jython is customized version of Python to work with Java Applications.

3. High Level Programming language:


Python is high level programming language and hence it is programmer friendly language.
Being a programmer we are not required to concentrate low level activities like memory
management and security etc..

4. Platform Independent:

Once we write a Python program,it can run on any platform without rewriting once again.
Internally PVM is responsible to convert into machine understandable form.

5. Portability:

Python programs are portable. ie we can migrate from one platform to another platform
very easily. Python programs will provide same results on any platform.

6. Dynamically Typed:

In Python we are not required to declare type for variables. Whenever we are assigning
the value, based on value, type will be allocated automatically.Hence Python is considered
as dynamically typed language.

But Java, C etc are Statically Typed Languages b'z we have to provide type at the beginning
only.

This dynamic typing nature will provide more flexibility to the programmer.

7. Both Procedure Oriented and Object Oriented:

Python language supports both Procedure oriented (like C, pascal etc) and object oriented
(like C++,Java) features. Hence we can get benefits of both like security and reusability etc

8. Interpreted:

We are not required to compile Python programs explcitly. Internally Python interpreter
will take care that compilation.

If compilation fails interpreter raised syntax errors. Once compilation success then PVM
(Python Virtual Machine) is responsible to execute.

9. Extensible:

We can use other language programs in Python.


The main advantages of this approach are:
1. We can use already existing legacy non-Python code
2. We can improve performance of the application

10. Embedded:

We can use Python programs in any other language programs.


i.e we can embed Python programs anywhere.

11. Extensive Library:

Python has a rich inbuilt library.


Being a programmer we can use this library directly and we are not responsible to
implement the functionality.

etc...

Limitations of Python:
1. Performance wise not up to the mark b'z it is interpreted language.
2. Not using for mobile Applications

Flavors of Python:

1. CPython:
It is the standard flavor of Python. It can be used to work with C lanugage Applications

2. Jython or JPython:
It is for Java Applications. It can run on JVM

3. IronPython:
It is for C#.Net platform

4. PyPy:
The main advantage of PyPy is performance will be improved because JIT compiler is
available inside PVM.

5. RubyPython
For Ruby Platforms

6. AnacondaPython
It is specially designed for handling large volume of data processing.
...
Python Versions:

Python 1.0V introduced in Jan 1994


Python 2.0V introduced in October 2000
Python 3.0V introduced in December 2008

Note: Python 3 won't provide backward compatibility to Python2


i.e there is no guarantee that Python2 programs will run in Python3.
Identifiers
A name in Python program is called identifier.
It can be class name or function name or module name or variable name.

a = 10

Rules to define identifiers in Python:


1. The only allowed characters in Python are

 alphabet symbols(either lower case or upper case)


 digits(0 to 9)
 underscore symbol(_)

Reserved Words

In Python some words are reserved to represent some meaning or functionality. Such type
of words are called Reserved words.

Note:
1. All Reserved words in Python contain only alphabet symbols.

2. Except the following 3 reserved words, all contain only lower case alphabet symbols.

 True
 False
 None

Eg: a= true 
a=True √

>>> import keyword


>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Data Types
Data Type represent the type of data present inside a variable.
In Python we are not required to specify the type explicitly. Based on value provided,the
type will be assigned automatically.Hence Python is Dynamically Typed Language.

Python contains the following inbuilt data types


1. int
2. float
3.complex
4.bool
5.str
6.bytes
7.bytearray
8.range
9.list
10.tuple
11.set
12.frozenset
13.dict
14.None

10
a = 10 a
a = 20
20

a
a = 10
b = 10 10
b

Note: Python contains several inbuilt functions

1.type()
to check the type of variable

2. id()
to get address of object
3. print()
to print the value

In Python everything is object

int data type:

We can use int data type to represent whole numbers (integral values)
Eg:
a=10
type(a) #int

Note:
In Python2 we have long data type to represent very large integral values.
But in Python3 there is no long type explicitly and we can represent long values also by
using int type only.

We can represent int values in the following ways

1. Decimal form
2. Binary form
3. Octal form
4. Hexa decimal form

1. Decimal form(base-10):

It is the default number system in Python


The allowed digits are: 0 to 9
Eg: a =10

2. Binary form(Base-2):

The allowed digits are : 0 & 1


Literal value should be prefixed with 0b or 0B

Eg: a = 0B1111
a =0B123
a=b111
3. Octal Form(Base-8):

The allowed digits are : 0 to 7


Literal value should be prefixed with 0o or 0O.

Eg: a=0o123
a=0o786

4. Hexa Decimal Form(Base-16):

The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed)
Literal value should be prefixed with 0x or 0X

Eg:
a =0XFACE
a=0XBeef
a =0XBeer

Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa
decimal forms. But PVM will always provide values only in decimal form.

a=10
b=0o10
c=0X10
d=0B10
print(a)10
print(b)8
print(c)16
print(d)2

Base Conversions
Python provide the following in-built functions for base conversions

1. bin():

We can use bin() to convert from any base to binary

Eg:

1) >>> bin(15)
2) '0b1111'
3) >>> bin(0o11)
4) '0b1001'
5) >>> bin(0X10)
6) '0b10000'

2. oct():

We can use oct() to convert from any base to octal


Eg:

1) >>> oct(10)
2) '0o12'
3) >>> oct(0B1111)
4) '0o17'
5) >>> oct(0X123)
6) '0o443'

3. hex():

We can use hex() to convert from any base to hexa decimal

Eg:

1) >>> hex(100)
2) '0x64'
3) >>> hex(0B111111)
4) '0x3f'
5) >>> hex(0o12345)
6) '0x14e5'

float data type:


We can use float data type to represent floating point values (decimal values)

Eg: f=1.234
type(f) float

We can also represent floating point values by using exponential form (scientific notation)

Eg: f=1.2e3
print(f) 1200.0
instead of 'e' we can use 'E'

The main advantage of exponential form is we can represent big values in less memory.
Complex Data Type:
A complex number is of the form

j2 = -1
a + bj
j = √−1
Real Part Imaginary Part

a and b contain intergers or floating point values

Eg:
3+5j
10+5.5j
0.5+0.1j

In the real part if we use int value then we can specify that either by decimal,octal,binary
or hexa decimal form.
But imaginary part should be specified only by using decimal form.

1) >>> a=0B11+5j
2) >>> a
3) (3+5j)
4) >>> a=3+0B11j
5) SyntaxError: invalid syntax

Even we can perform operations on complex type values.

1) >>> a=10+1.5j
2) >>> b=20+2.5j
3) >>> c=a+b
4) >>> print(c)

We can use complex type generally in scientific Applications and electrical engineering
Applications.

4. bool data type:

We can use this data type to represent boolean values.


The only allowed values for this data type are:
True and False

Internally Python represents True as 1 and False as 0

b=True
type(b) =>bool

Eg:
a=10
b=20
c=a<b
print(c)==>True

True+True==>2
True-False==>1

str type:
str represents String data type.

A String is a sequence of characters enclosed within single quotes or double quotes.

s1='durga'
s1="durga"

By using single quotes or double quotes we cannot represent multi line string literals.

s1="durgesh”

ORr this requirement we should go for triple single quotes(''') or triple double quotes(""")

s1='''cybrom
soft'''

s1="""cybrom
soft"""
Type Casting
We can convert one type value to another type. This conversion is called Typecasting or
Type coersion.
The following are various inbuilt functions for type casting.

1. int()
2. float()
3. complex()
4. bool()
5. str()

1.int():

We can use this function to convert values from other types to int

Eg:

1) >>> int(123.987)
2) 123
3) >>> int(10+5j)
4) TypeError: can't convert complex to int
5) >>> int(True)
6) 1
7) >>> int(False)
8) 0
9) >>> int("10")
10) 10
11) >>> int("10.5")
12) ValueError: invalid literal for int() with base 10: '10.5'
13) >>> int("ten")
14) ValueError: invalid literal for int() with base 10: 'ten'
15) >>> int("0B1111")
16) ValueError: invalid literal for int() with base 10: '0B1111'

Note:

1. We can convert from any type to int except complex type.


2. If we want to convert str type to int type, compulsary str should contain only integral
value and should be specified in base-10
2. float():

We can use float() function to convert other type values to float type.

1) >>> float(10)
2) 10.0
3) >>> float(10+5j)
4) TypeError: can't convert complex to float
5) >>> float(True)
6) 1.0
7) >>> float(False)
8) 0.0
9) >>> float("10")
10) 10.0
11) >>> float("10.5")
12) 10.5
13) >>> float("ten")
14) ValueError: could not convert string to float: 'ten'
15) >>> float("0B1111")
16) ValueError: could not convert string to float: '0B1111'

Note:
1. We can convert any type value to float type except complex type.

2. Whenever we are trying to convert str type to float type compulsary str should be
either integral or floating point literal and should be specified only in base-10.

3. complex():

We can use complex() function to convert other types to complex type.

Form-1: complex(x)
We can use this function to convert x into complex number with real part x and imaginary
part 0.

Eg:

1) complex(10)==>10+0j
2) complex(10.5)===>10.5+0j
3) complex(True)==>1+0j
4) complex(False)==>0j
5) complex("10")==>10+0j
6) complex("10.5")==>10.5+0j
7) complex("ten")
8) ValueError: complex() arg is a malformed string
Form-2: complex(x,y)

We can use this method to convert x and y into complex number such that x will be real
part and y will be imaginary part.

Eg: complex(10,-2)==>10-2j
complex(True,False)==>1+0j

4. bool():

We can use this function to convert other type values to bool type.

Eg:

1) bool(0)==>False
2) bool(1)==>True
3) bool(10)===>True
4) bool(10.5)===>True
5) bool(0.178)==>True
6) bool(0.0)==>False
7) bool(10-2j)==>True
8) bool(0+1.5j)==>True
9) bool(0+0j)==>False
10) bool("True")==>True
11) bool("False")==>True
12) bool("")==>False
Operators
Operator is a symbol that performs certain operations.
Python provides the following set of operators

1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise oeprators
5. Assignment operators
6. Special operators

1. Arithmetic Operators:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulo operator

// ==>Floor Division operator

** ==>Exponent operator or power operator

Eg: test.py:

1) a=10
2) b=2
3) print('a+b=',a+b)
4) print('a-b=',a-b)
5) print('a*b=',a*b)
6) print('a/b=',a/b)
7) print('a//b=',a//b)
8) print('a%b=',a%b)
9) print('a**b=',a**b)
Output:

1) Python test.py or py test.py


2) a+b= 12
3) a-b= 8
4) a*b= 20
5) a/b= 5.0
6) a//b= 5
7) a%b= 0
8) a**b= 100

Eg:

1) a = 10.5
2) b=2
3)
4) a+b= 12.5
5) a-b= 8.5
6) a*b= 21.0
7) a/b= 5.25
8) a//b= 5.0
9) a%b= 0.5
10) a**b= 110.25

Eg:
10/2==>5.0
10//2==>5
10.0/2===>5.0
10.0//2===>5.0

Note: / operator always performs floating point arithmetic. Hence it will always returns
float value.

But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If atleast one argument is float type then
result is float type.

Note:

We can use +,* operators for str type also.


If we want to use + operator for str type then compulsory both arguments should be str
type only otherwise we will get error.

1) >>> "durga"+10
2) TypeError: must be str, not int
3) >>> "durga"+"10"
4) 'durga10'
If we use * operator for str type then compulsory one argument should be int and other
argument should be str type.

2*"durga"
"durga"*2
2.5*"durga" ==>TypeError: can't multiply sequence by non-int of type 'float'
"durga"*"durga"==>TypeError: can't multiply sequence by non-int of type 'str'

+====>String concatenation operator


* ===>String multiplication operator

Note: For any number x,

x/0 and x%0 always raises "ZeroDivisionError"

10/0
10.0/0
.....

Relational Operators:
>,>=,<,<=

Eg 1:

1) a=10
2) b=20
3) print("a > b is ",a>b)
4) print("a >= b is ",a>=b)
5) print("a < b is ",a<b)
6) print("a <= b is ",a<=b)
7)
8) a > b is False
9) a >= b is False
10) a < b is True
11) a <= b is True

We can apply relational operators for str types also

Eg 2:

1) a="durga"
2) b="durga"
3) print("a > b is ",a>b)
4) print("a >= b is ",a>=b)
5) print("a < b is ",a<b)
6) print("a <= b is ",a<=b)
7)
8) a > b is False
9) a >= b is True
10) a < b is False
11) a <= b is True

Eg:

1) print(True>True) False
2) print(True>=True) True
3) print(10 >True) True
4) print(False > True) False
5)
6) print(10>'durga')
7) TypeError: '>' not supported between instances of 'int' and 'str'

Eg:

1) a=10
2) b=20
3) if(a>b):
4) print("a is greater than b")
5) else:
6) print("a is not greater than b")

Outputa is not greater than b

Note: Chaining of relational operators is possible. In the chaining, if all comparisons


returns True then only result is True. If atleast one comparison returns False then the
result is False

Eg:

1) 10<20 ==>True
2) 10<20<30 ==>True
3) 10<20<30<40 ==>True
4) 10<20<30<40>50 ==>False

equality operators:
== , !=

We can apply these operators for any type even for incompatible types also

1) >>> 10==20
2) False
3) >>> 10!= 20
4) True
5) >>> 10==True
6) False
7) >>> False==False
8) True
9) >>> "durga"=="durga"
10) True
11) >>> 10=="durga"
12) False

Note: Chaining concept is applicable for equality operators. If atleast one comparison
returns False then the result is False. otherwise the result is True.

Eg:

1) >>> 10==20==30==40
2) False
3) >>> 10==10==10==10
4) True

Logical Operators:
and, or ,not

We can apply for all types.

For boolean types behaviour:

and ==>If both arguments are True then only result is True
or ====>If atleast one arugemnt is True then result is True
not ==>complement

True and False ==>False


True or False ===>True
not False ==>True

For non-boolean types behaviour:

0 means False
non-zero means True
empty string is always treated as False

x and y:

==>if x is evaluates to false return x otherwise return y


Eg:
10 and 20
0 and 20

If first argument is zero then result is zero otherwise result is y

x or y:

If x evaluates to True then result is x otherwise result is y

10 or 20 ==> 10
0 or 20 ==> 20

not x:

If x is evalutates to False then result is True otherwise False

not 10 ==>False

not 0 ==>True

Eg:

1) "durga" and "durgasoft" ==>durgasoft


2) "" and "durga" ==>""
3) "durga" and "" ==>""
4) "" or "durga" ==>"durga"
5) "durga" or ""==>"durga"
6) not ""==>True
7) not "durga" ==>False

Bitwise Operators:
We can apply these operators bitwise.
These operators are applicable only for int and boolean types.
By mistake if we are trying to apply for any other type then we will get Error.

&,|,^,~,<<,>>

print(4&5) ==>valid
print(10.5 & 5.6) ==>
TypeError: unsupported operand type(s) for &: 'float' and 'float'

print(True & True) ==>valid


& ==> If both bits are 1 then only result is 1 otherwise result is 0
| ==> If atleast one bit is 1 then result is 1 otherwise result is 0
^ ==>If bits are different then only result is 1 otherwise result is 0
~ ==>bitwise complement operator
1==>0 & 0==>1
<< ==>Bitwise Left shift
>> ==>Bitwise Right Shift

print(4&5) ==>4
print(4|5) ==>5
print(4^5) ==>1

Operator Description
& If both bits are 1 then only result is 1 otherwise result is 0
| If atleast one bit is 1 then result is 1 otherwise result is 0
^ If bits are different then only result is 1 otherwise result is 0
~ bitwise complement operator i.e 1 means 0 and 0 means 1
>> Bitwise Left shift Operator
<< Bitwise Right shift Operator

bitwise complement operator(~):

We have to apply complement for total bits.

Eg: print(~5) ==>-6

Note:
The most significant bit acts as sign bit. 0 value represents +ve number where as 1
represents -ve value.
positive numbers will be repesented directly in the memory where as -ve numbers will be
represented indirectly in 2's complement form.

Shift Operators:
<< Left shift operator
After shifting the empty cells we have to fill with zero

print(10<<2)==>40

0 0 0 0 1 0 1 0

0 0 1 0 1 0 0 0
>> Right Shift operator

After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve)

print(10>>2) ==>2

0 0 0 0 1 0 1 0

0 0 0 0 0 0 1 0

We can apply bitwise operators for boolean types also

print(True & False) ==>False


print(True | False) ===>True
print(True ^ False) ==>True
print(~True) ==>-2
print(True<<2) ==>4
print(True>>2) ==>0

Assignment Operators:
We can use assignment operator to assign value to the variable.

Eg:
x=10

We can combine asignment operator with some other operator to form compound
assignment operator.

Eg: x+=10 ====> x = x+10

The following is the list of all possible compound assignment operators in Python

+=
-=
*=
/=
%=
//=
**=
&=
|=
^=
>>=
<<=

Eg:

1) x=10
2) x+=20
3) print(x) ==>30

Eg:

1) x=10
2) x&=5
3) print(x) ==>0

Ternary Operator:
Syntax:
x = firstValue if condition else secondValue

If condition is True then firstValue will be considered else secondValue will be considered.

Eg 1:

1) a,b=10,20
2) x=30 if a<b else 40
3) print(x) #30

Eg 2: Read two numbers from the keyboard and print minimum value

1) a=int(input("Enter First Number:"))


2) b=int(input("Enter Second Number:"))
3) min=a if a<b else b
4) print("Minimum Value:",min)

Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
STRING MANIPULATION
Counting substring in the given String:
We can find the number of occurrences of substring present in the given string by using count()
method.

1. s.count(substring) ==> It will search through out the string


2. s.count(substring, bEgin, end) ===> It will search from bEgin index to end-1 index

1) s="abcabcabcabcadda"
2) print(s.count('a'))
3) print(s.count('ab'))
4) print(s.count('a',3,7))

Output:
6
4
2

Replacing a string with another string:


s.replace(oldstring,newstring)

inside s, every occurrence of oldstring will be replaced with newstring.

Eg1:
s="Learning Python is very difficult"
s1=s.replace("difficult","easy")
print(s1)

Output:
Learning Python is very easy

Eg2: All occurrences will be replaced

s="ababababababab"
s1=s.replace("a","b")
print(s1)

Output: bbbbbbbbbbbbbb

Q. String objects are immutable then how we can change the content by
using replace() method.
Once we creates string object, we cannot change the content.This non changeable behaviour is
nothing but immutability. If we are trying to change the content by using any method, then with
those changes a new object will be created and changes won't be happend in existing object.

Hence with replace() method also a new object got created but existing object won't be changed.
Eg:
s="abab"
s1=s.replace("a","b")
print(s,"is available at :",id(s))
print(s1,"is available at :",id(s1))

Output:
abab is available at : 4568672
bbbb is available at : 4568704

In the above example, original object is available and we can see new object which was created
because of replace() method.

Splitting of Strings:
We can split the given string according to specified seperator by using split() method.

l=s.split(seperator)

The default seperator is space. The return type of split() method is List

Eg1:

1) s="durga software solutions"


2) l=s.split()
3) for x in l:
4) print(x)

Output:
durga
software
solutions

Eg2:

1) s="22-02-2018"
2) l=s.split('-')
3) for x in l:
4) print(x)

Output:
22
02
2018
Joining of Strings:
We can join a group of strings(list or tuple) wrt the given seperator.

s=seperator.join(group of strings)

Eg:
t=('sunny','bunny','chinny')
s='-'.join(t)
print(s)

Output: sunny-bunny-chinny

Eg2:
l=['hyderabad','singapore','london','dubai']
s=':'.join(l)
print(s)

hyderabad:singapore:london:dubai

Changing case of a String:


We can change case of a string by using the following 4 methods.

1. upper()===>To convert all characters to upper case


2. lower() ===>To convert all characters to lower case
3. swapcase()===>converts all lower case characters to upper case and all upper case characters to
lower case
4. title() ===>To convert all character to title case. i.e first character in every word should be upper
case and all remaining characters should be in lower case.
5. capitalize() ==>Only first character will be converted to upper case and all remaining characters
can be converted to lower case

Eg:
s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())

Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy

Checking starting and ending part of the string:


Python contains the following methods for this purpose

1. s.startswith(substring)
2. s.endswith(substring)

Eg:
s='learning Python is very easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))

Output:
True
False
True

To check type of characters present in a string:


Python contains the following methods for this purpose.

1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 )


2) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z)
3) isdigit(): Returns True if all characters are digits only( 0 to 9)
4) islower(): Returns True if all characters are lower case alphabet symbols
5) isupper(): Returns True if all characters are upper case aplhabet symbols
6) istitle(): Returns True if string is in title case
7) isspace(): Returns True if string contains only spaces

Eg:
print('Durga786'.isalnum()) #True
print('durga786'.isalpha()) #False
print('durga'.isalpha()) #True
print('durga'.isdigit()) #False
print('786786'.isdigit()) #True
print('abc'.islower()) #True
print('Abc'.islower()) #False
print('abc123'.islower()) #True
print('ABC'.isupper()) #True
print('Learning python is Easy'.istitle()) #False
print('Learning Python Is Easy'.istitle()) #True
print(' '.isspace()) #True
Formatting the Strings:
We can format the strings with variable values by using replacement operator {} and format()
method.

Eg name='durga' salary=10000 age=48


print("{} 's salary is {} and his age is {}".format(name,salary,age)) print("{0} 's salary is {1} and his age is
{2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))

Output:
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48

Accessing elements :
We can access elements either by using index or by using slice operator(:)

1. By using index:

Array follows zero based index. ie index of first element is


zero.Array supports both +ve and -ve indexes.
+ve index meant for Left to Right
-ve index meant for Right to Left

Ex: list=[10,20,30,40]

-4 -3 -2 -1
10 20 30 40
0 1 2 3
print(list[0]) ==>10
print(list[-1]) ==>40

Ex:2 a=”codeofpython”
Print(a[2])
Output:d

2. By using slice operator:

Syntax:

[start:stop:step]
start ==>it indicates the index where slice has to start
default value is 0

stop ===>It indicates the index where slice has to end


default value is max allowed index of list ie length of the list

step ==>increment value


default value is 1
+ve index meant for Left to Right
-ve index meant for Right to Left

Eg:

1) n=[1,2,3,4,5,6,7,8,9,10]
2) print(n[2:7:2])
3) print(n[4::2])
4) print(n[3:7])
5) print(n[8:2:-2])
6) print(n[4:100])

Eg:
a='codeofpython'
print(a[:])
print(a[0:])
print(a[:3])
print(a[:-3])
print(a[-2:-6:2])
print(a[-2:-6:-1])
print(a[-1::-1])
print(a[-1:-1:-1])
print(a[0:0])
Mathematical Functions (math Module)
A Module is collection of functions, variables and classes etc.

math is a module that contains several functions to perform mathematical operations

If we want to use any module in Python, first we have to import that module.

import math

Once we import a module then we can call any function of that module.

import math
print(math.sqrt(16))
print(math.pi)

Note:We can create alias name by using as keyword.

import math as m

Once we create alias name, by using that we can access functions and variables of that
module

import math as m
print(m.sqrt(16))
print(m.pi)

We can import a particular member of a module explicitly as follows

from math import sqrt


from math import sqrt,pi

If we import a member explicitly then it is not required to use module name while
accessing.

from math import sqrt,pi


print(sqrt(16))
print(pi)

important functions of math module:

ceil(x) ,floor(x) pow(x,y) factorial(x)trunc(x) gcd(x,y) sin(x),cos(x),tan(x) ------


Reading dynamic input from the keyboard:
input():
input() function can be used to read data directly in our required format.We are notrequired to
perform type casting.

x=input("Enter Value)
type(x)
Note:By default it takes string

For explicit type, we have to use type conversion.

x=int(input("Enter Value))
type(x)
Now it will take value as integer.

How to read multiple values from the keyboard in a single line:

a,b= [int(x) for x in input("Enter 2 numbers :").split()]


print("Product is :", a*b)

Note: split() function can take space as seperator by defaul.But we can pass
anything as seperator.

eval():eval Function take a String and evaluate the Result.

Eg: x = eval(“10+20+30”)
print(x)
Output: 60
Eg: x = eval(input(“Enter Expression”))
Enter Expression: 10+2*3/4
Output11.5
Flow Control
Flow control describes the order in which statements will be executed at runtime.

Control Flow

Conditional Transfer Iterative


Statements Statements Statements

1) if 1) break 1) for
2) if-elif 2) continue 2) while
3) if-elif-else 3) pass

I. Conditional Statements
1) if

if condition : statement

or

if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be executed.
Eg:

1) name=input("Enter Name:")
2) if name=="durga" :
3) print("Hello Durga Good Morning")
4) print("How are you!!!")

2) if-else:
if condition :
Action-1
else :
Action-2

if condition is true then Action-1 will be executed otherwise Action-2 will be executed.

Eg:

1) name=input("Enter Name:")
2) if name=="durga" :
3) print("Hello Durga Good Morning")
4) else:
5) print("Hello Guest Good Moring")
6) print("How are you!!!")
3) if-elif-else:
Syntax:

if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
...
else:
Default Action

Based condition the corresponding action will be executed.

Eg:

1) brand=input("Enter Your Favourite Brand:")


2) if brand=="RC" :
3) print("It is childrens brand")
4) elif brand=="KF":
5) print("It is not that much kick")
6) elif brand=="FO":
7) print("Buy one get Free One")
8) else :
9) print("Other Brands are not recommended")
Note:

1. else part is always optional


Hence the following are various possible syntaxes.
1. if
2. if - else
3. if-elif-else
4.if-elif

2. There is no switch statement in Python


II. Iterative Statements
If we want to execute a group of statements multiple times then we should go for
Iterative statements.

Python supports 2 types of iterative statements.

1. for loop
2. while loop

1) for loop:
If we want to execute some action for every element present in some sequence(it may be
string or collection)then we should go for for loop.

Syntax:

for x in sequence :
body

where sequence can be string or any collection.


Body will be executed for every element present in the sequence.

Eg 1: To print characters present in the given string

1) s="Sun bright"
2) for x in s :
3) print(x)

1) while loop:
If we want to execute a group of statements iteratively until some condition false,then we
should go for while loop.

Syntax:

while condition :
body

Eg: To print numbers from 1 to 10 by using while loop

1) x=1
2) while x <=10:
3) print(x)
4) x=x+1
Infinite Loops:
1) i=0;
2) while True :
3) i=i+1;
4) print("Hello",i)

Nested Loops:
Sometimes we can take a loop inside another loop,which are also known as nested loops.

Eg:

1) for i in range(4):
2) for j in range(4):
3) print("i=",i," j=",j)
4)
5) Output
6) D:\Cybrom_classes>py test.py
7) i= 0 j= 0
8) i= 0 j= 1
9) i= 0 j= 2
10) i= 0 j= 3
11) i= 1 j= 0
12) i= 1 j= 1
13) i= 1 j= 2
14) i= 1 j= 3
15) i= 2 j= 0
16) i= 2 j= 1
17) i= 2 j= 2
18) i= 2 j= 3
19) i= 3 j= 0
20) i= 3 j= 1
21) i= 3 j= 2
22) i= 3 j= 3
III. Transfer Statements
1) break:
We can use break statement inside loops to break loop execution based on some
condition.

Eg:

1) for i in range(10):
2) if i==7:
3) print("processing is enough..plz break")
4) break
5) print(i)

2) continue:
We can use continue statement to skip current iteration and continue next iteration.

Eg 1: To print odd numbers in the range 0 to 9

1) for i in range(10):
2) if i%2==0:
3) continue
4) print(i)
loops with else block:

Inside loop execution,if break statement not executed ,then only else part will
beexecuted.

else means loop without

breakEg:

1) cart=[10,20,30,40,50]
2) for item in cart:
3) if item>=500:
4) print("We cannot process this order")
5) break
6) print(item)
7) else:
8) print("Congrats ...all items processed successfully")

Q. What is the difference between for loop and while loop in Python?

We can use loops to repeat code execution


Repeat code for every item in sequence ==>for loop
Repeat code as long as condition is true ==>while
loop

Q. How to exit from the


loop?by using break
statement

Q. How to skip some iterations inside


loop?by using continue statement.

Q. When else part will be executed wrt loops?


If loop executed without break

3) pass statement:
pass is a keyword in Python.
In our programming syntactically if block is required which won't do anything then
we candefine that empty block with pass keyword.

pass
|- It is an empty statement
|- It is null statement
|- It won't do

anything

Eg:

if True:
SyntaxError: unexpected EOF while parsing

if True: pass
==>valid

Use case of pass:

Sometimes in the parent class we have to declare a function with empty body and
childclass responsible to provide proper implementation. Such type of empty body
we can define by using pass keyword. (It is something like abstract method in java)

del statement:

del is a keyword in Python.

After using a variable, it is highly recommended to delete that variable if it is no longer


required,so that the corresponding object is eligible for Garbage Collection.
We can delete variable by using del

keyword.Eg:

1) x=10
2) print(x)
3) del x
After deleting a variable we cannot access that variable otherwise we will get
NameError.Eg:
1) x=10
2) del x
3) print(x)

NameError: name 'x' is not defined.

Note:
We can delete variables which are pointing to immutable objects.But we cannot
deletethe elements present inside immutable object.

Eg:

1) s="Cybrom"
2) print(s)
3) del s==>valid
4) del s[0] ==>TypeError: 'str' object doesn't support item deletion

Difference between del and None:

In the case del, the variable will be removed and we cannot access that variable(unbind
operation)

1) s="Cybrom"
2) del s
3) print(s) ==>NameError: name 's' is not defined.

But in the case of None assignment the variable won't be removed but the
correspondingobject is eligible for Garbage Collection(re bind operation). Hence after
assigning with None value,we can access that variable.

1) s="Cybrom"
2) s=None
3) print(s) # None

------------------------------***PART-1-END -SECTION***--------------------------------------------------------

You might also like