Python Notes
Python Notes
• These operator is use to perform arithmetic operation like addition , sub , div etc
a = 15
b=4
output : 19
output : 60
Output : 11
/*Power Operator*/
c=a**b
It is said as power of
a=15
b=4
c= a**b
Float Division ( / ) : dividing two integers, but the result I am getting it as float because it is dividing
completely.
a=15
b=4
c=a/b
print(c)
3.75
dividend :15,
devisor: 4
4 ) 15 ( 3.75
14
03
28
20
20
00 reminder
Floor division ( // ) :
• If we don’t want in float form, we want in int form then we will use floor division
C = a // b =3
Mod ( %) :
• This will divide . It will not take quotient it will take remainder
a = 15
b=4
Z = x//y = 3
Z = x % y =0
A=15
B=4
C=a+b
C
C=a-b
D =a*b
E =a**b
F =a/b
G =a//b
Expression
The instruction that you write using operators.
If we are using operators in a instructions or a statement of program, then it is called as
expression.
Expressions
• The instruction that we write using operators is called expressions
c =a+b
# c , a , b are operands
take example :
d = 2+3*5
#3*5=15
d = 2+15
d=17
d = 2*3 + 8/2
=6+4
= 10
2+3*5 # first multiplication take place because it have higher precedence than addition
2+15 = 17
By using parentheses
(2+3) * 5 # here addition will take place because parentheses have higher precedence than all
5 * 5 = 25
• What if we are having
Python expressions :
Square .
Area of a square = lb
l*b
Triangle .
In python = 1/2*b*h
Trapezium
Rhombus area
Displacement
2 2
(v -u /2a)
In python
(v**2-u**2)/(2*a)
Equal roots
(-b/2a)
In python using expressions
(-b/(2*a))
# it has 6 sides
Total = 2(lh+lb+bh)
In python Program
L = float(input('Enter length'))
B = float(input('Enter Breadth'))
H = float(input('Enter Height'))
Area = 2 * (L * B + L * H + B * H)
print('Total Surface Area is ', Area)
Quadratic
eg : ax2 + bx + c = 0
Roots :
r1 = -b + √ b2-4ac / 2a
r2 = -b - √ b2-4ac / 2a
If √ b2-4ac will give negative value than it will become complex number
In python Program
import math
a = int(input('Enter a value'))
b = int(input('Enter b value'))
c = int(input('Enter c value'))
r1 = (-b + math.sqrt(b**2 - 4 * a * c ))/(2 * a)
r2 = (-b - math.sqrt(b**2 - 4 * a * c ))/(2 * a)
print('Roots are :-')
print('Root1', r1)
print('Root2', r2)
Output
Enter a value6
Enter b value11
Enter c value4
Roots are
Root1 -0.5
Root2 -1.3333333333333333
a=a+1
a=5+1
stores 6 in a
Count= 0
Count= count+1
Count = count+1. This type of statements can be written in short like count+=1
a=a+1 instead of writing this elaborated statement we can write it in short like a+=1.
This statement was for addition
subtraction
Now, in same way if we have anything to subtract we can use subtraction.
N=10
N=n-1
n-=1
this means the same thing n- assigns 1
multiplication
if we have a variable p=10 and we want to multiply it with a variable x=5
p*=x
Bitwise operators
bitwise operators can also be used with these assignment operators.
If we have two variables a=10, b=14 and want to perform & operation
a=a & b
a& =b
• This table shows how operators are compatible with other Datatypes.
• If you are performing float division you'll get float result.
• If you are performing floor division you'll get integer result.
True = 1 , False = 0
Boolean
True = 1 , False = 0
String
• Adding 2 strings is called ‘concatenation ’. If one type is integer and the other is string concatenation
doesn't work. The 2 types to be added should be string only.
• In multiplication I.e, * one type should be string and the other should be an integer only. • Float
doesn’t work for strings.
Conditional statements
• Control statements are the statements that control the flow of execution of statements so that they
can be executed repeatedly and randomly
• Whenever we write a program it will execute linearly but in set of statement we add conditions it
will break the linear execution and will execute the conditional statement ( if else ) then go further
if
• First the condition is tested If condition is true it will execute . if block is false than it will execute
else block .
• We can write one or more statement after colon ( : )
• if is false , then the statement mentioned after : are not executed • Lets see the syntax :
if condition :
statements
• We can see in syntax there is indentation . Indentation is important in python . It is used in the
beginning of the statement
if else
• The if ….else executes statement evaluates test expression and will execute the block of if only when
the test condition is True.
• If the condition is False, the body of else is executed. Indentation is used to separate the blocks.
if condition :
statement else :
statement
• For writing the conditions we use relational and logical operators and the output will be always be “
True “ or “ False “
• This is also called as comparison operators
a = 10 b = 20
if a < b : T
a <= b : T
a>b : F
a >= b : F
a == b : F
a != b : T
Logical
• Logical operators use to write compound conditions
li AND
• Lets take example - cond1 and cond2
• If the cond1 and cond2 both are true than it will return true value
True - 1 False - 0
50 100
• Lets take an example about subjects (maths , phy , and chem ) where above 45 will be the passing
marks
lii OR
• If the cond1 or cond2 both are false returns false
• OR is like addition
50 100
if x <= 50 or x >=100 :
liii NOT
• It will negate it
• Returns the opposite value ( If its true returns false if its false return true )
• It is not commonly used
Introduction to string
Programs to Exexcute
s = 'Hello'
type(s)
O/P
<class 'str'>
s1 = 'HI'
s2 =input('Enter String')
Enter String welcome
type(s1)
#O/P
<class 'str'>
type(s2)
#O/P
<class 'str'>
# need to find length of s2
len(s2)
#O/P
8
s1 = 'Hello'
for x in s1:
print(x)
O/P
H
e
l
l
o
• When a string value is given directly in the program then its called string literals
• String literals can be in ‘ ’ , “ ” , ‘’ ‘’ , “” “”
• When a string already contains a single quote ( inner quotes ) then you should enclose the string in
double quotes (outer quotes ) and vice versa
Ex : s = “ John ’ s ”
or
s ='John"s'
print (s)
or
s ='John"s'
print (s)
John"s
s1= 'Joins"'
print(s1)
O/P
Joins"
John"s
If a string is in multiple lines then you have to use triple single quotes (or) triple double quotes
Ex : ‘ ‘ ‘ hello
or
“ “ “ hello
Operators on String
Concatenation :
s1 = 'Hello'
s2 = 'world'
S3 = s1+s2
print(S3)
O/p
Helloworld
• It will concatenate the two string and gives the new string . Because string is immutable it will
not modify it . It will create a new string
>>>S4 = 'Hello' ' ' 'world'
Print(S4)
s5= 'hello' + 5
S5 = 'HI'+str(5)
print (S5)
Output : HI5
Repetition
s1 = 'hi'
s1 * 3
Output : hihihi
• You can have same string multiple times by using multiplication s1 * 2.5
S1= 'Hello'
Indexing :
s1 = ‘ hello world ‘
• You can access any character of the string using index also called as substring s1[ 4 ] —— o
s1[ 6 ] —— w s1[ -5 ] —— o
Slicing :
s1 [start : end : step ]
• Slicing will work just like loop
• To print a string in reverse we use -ve indexing , starting from -1
• Suppose if a string stops at -11 [ n ] then we should write -12 [ n-1 ] in the slicing operator to
get -11.
• If we do not give an end point in slicing it takes the default value (I.e, where the list ends )
automatically , same goes for start point (default is 0) and stepsize (default is 1).
• Instead of using range based for loop we can use slicing to get the same result.
• Slicing gives a separate string.
s1[0:len(s1):1]
>>>
s1[:len(s1):1]
s1[::2]
O/p: 'hlowrd'
s1[3::]
s1[6:8]
O/p: 'wo'
s1[::-1]
s1[:-len(s1)-1:-1]
s1[-1::-1]
s1[-1::-2]
O/p: 'drwolh'
in :
• It will say if a character is present in the string or not .
• If it is present then it will return True or else False .
• in , not in is also called as Membership operator.
• in , not in make case sensitive comparison. (it considers lower and upper case differently)
Present - True
Not present - False
me in s1 —— False
not in :
It will say if it is not present . Then it will return True or else False .
'me' not in s1
O/P True
'world' not in s1
O/p False
dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition',
'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']String Method
• Methods are the member of the class which performs operation upon the data of an object
s.find (‘ how ‘)
O/p: 7
s.find(‘ k ‘)
O/p: -1 . [Why it is -1 because the character will start from 0 . -1 means outside the range . So it is
invalid position . ]
s.find ( ‘ o ‘ , 5 )
sub start
• If you want to find out after the 5th index we write 5 in starting index
• If you want to find out other substring then you should give starting and ending index
s . find (‘o’ , 5 , 7 )
It will check from 5 to 7
s.rfind(‘o’)
s.find (‘o ‘ , 0 , 15 )
• In rfind ending index will work but in find starting index will work
s.index ( )
s = 'Hello, how are you'
• s.index and s.find is same but have minor differences . rindex is same as rfind s.count( )
• The count gives counting of the string. It will not gives all the indexes . It will only count
s.count('a') 1
s.count('H') 1
s.count(‘are’) 1
s.ljust(width[,fill])
s.rjust(width[,fill])
s.center(width[,fill])
s = ‘ python ‘
s.rjust ( )
s.center ( )
s.center(10 , ‘ # ‘ )
s.ljust(3)
• It will take the entire string it will not just take 3 letters
• If you want bigger space you mention the width bigger than the length of the string • All this have one
more parameter that is fill
s.center(10 , ‘ * ‘ )
• Python have only 6 alphabets but we want 10 spaces . * will be filled in empty spaces • 10 space
vacant spaces with * otherwise it will fill with spaces
s = python
Removing Spaces
• String is immutable so it will not modify it will create a new string
s.strip ([ chars ])
s.lstrip ([ chars ]) this is useful for removing the characters from the string
s.rstrip ([ chars ])
• They remove leading char , tailing characters and characters from both sides … by default they will
remove spaces
s.lstrip - it will remove leading char
s. lstrip (‘ . ‘ ) ———> it will remove leading dots and stops when there is no dot
O/p - 'PPpython'
• All this methods will return new string they will generate new string after performing the operations
Changing Case
s.capitalize( )
s.lower( )
s.upper( )
s.title( )
s.swapcase( )
s.casefold( )
b.capitalize()
b.lower()
b.swapcase()
b.title()
b.casefold()
String Methods
s.isupper( )
s.islower( )
s.istitle ( )
s.isalnum ( )
s.isalpha ( )
s.isspace ( )
s.isascii ( )
s.isupper( )
s = ‘ HELLO ‘
s.isupper()
O/p: True
b= 'Nivedita Hiremath'
b.isupper()
O/p: Flase
It will return true if only all the alphabets are in capital letters
s.islower( )
s = ‘ hello ‘
s.islower()
O/p true
b.islower()
O/p: Flase
It will return false because all should be in lower case but in this O is capital so its false
s.istitle ( )
Every starting letter should be capital so it will return True and empty string will return False .
s.isalnum ( )
• If the string contain alphabets and numbers it will return true . If it contain special alphabets than it
will return false
s = ‘ abc-123’
s1.isalnum()
S='abc123’
S.isalnum()
True
s.isalpha ( )
s.isspace ( )
• It will check if there are any spaces present in the string then it will return true
s.isascii ( )
• If it contain all the ASCII character , can have lower case , upper case , special character etc then it will
return True
Q1=‘ abc12#! ‘
Q1.isascii()——> True
s = ‘ length1 ‘
s.isprintable( )
• All the ASCII letters , other language letters are printable but there are escape characters \n \t \r are
not printable so it will return false
s = ‘ hello ‘
s.isprintable()——> True
s = ‘ 1.25 ‘ ——>False
s.isdigit( )
s.isnumeric( )
s = ‘ 5 ‘ ——> True
1/2