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

Python Notes

The document discusses arithmetic operators and expressions in Python. It explains different arithmetic operators like addition, subtraction, multiplication, power, float division, floor division, modulo and assignment operators. It also covers operator precedence and various examples of writing arithmetic expressions in Python programs.

Uploaded by

Nisha Monisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python Notes

The document discusses arithmetic operators and expressions in Python. It explains different arithmetic operators like addition, subtraction, multiplication, power, float division, floor division, modulo and assignment operators. It also covers operator precedence and various examples of writing arithmetic expressions in Python programs.

Uploaded by

Nisha Monisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Operators ( Arithmetic operators )

• These operator is use to perform arithmetic operation like addition , sub , div etc

• There are 7 athematic operators

a = 15

b=4

c = a+b /* addition Operator*/

output : 19

c = a*b /* multiplication Operator*/

output : 60

c =a-b. /* Sub Operator */

Output : 11

/*Power Operator*/

c=a**b

• Now the question is what is **

It is said as power of

a=15

b=4

c= a**b

(15 )^4 = 50,625

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

 So, this division gives the result in integer form


 It will not take decimal point.

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

# = , + are operators Lets

take example :

d = 2+3*5

#3*5=15

d = 2+15

d=17

• This happened because of precedence .


• First multiplication takes place because it has higher precedence than addition

• They will execute based on their precedence

d = 2*3 + 8/2
=6+4

= 10

• To increase the precedence we use ( )

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

d=3*4*5/4 # * , / have same precedence

So it will do left to right #first multiplication than division


d=2**3**2 (for expo operation will take place from right to left)

It will execute from right to left

Python expressions :
Square .

Area of a square = lb

• In python we write using expressions

The area of the square can be written

l*b

Triangle .

Area of a triangle = 1/2 bh

In python = 1/2*b*h

Trapezium

Area of a trapezium = a+b/2 h


• In python we write using python expressions area= (a+b) / 2*h

Rhombus area

Area = ½*(a+b)*h (In python)

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))

Total surface Area of a cuboid

# it has 6 sides

Front and back = 2l*h

Bottom and top = 2lh

Left and right = 2bh

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

Finding roots of quadratic equations

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

Assignment arithmetic operator

Arithmetic operator joined with assignment operator.

 suppose we have a variable


a=5

a=a+1

a=5+1

stores 6 in a

 whatever the value is stored results into it.

 It means we want to modify the value of a and increase it by 1

 The a is assigned two timws the value of a is taken and increased by 1

So, this type of statements usually used for counting

Count= 0

Count= count+1

this means 1= 0+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

then we may be assigning p=p*x

p*=x

to make the statements short this operations are given

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

Arithmetic with all type

• 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

• Bool v/s Bool the result will always be integer.


• Bool v/s complex the result will always be complex.
Complex

• Complex with integer the result is always complex.


• Complex works with all except // and % as // is used to convert float type to int type but can a
complex number do all this , no so it doesn't work same goes for %.

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.

• Lets see syntax for if else statement

if condition :
statement else :
statement

Relational and logical operator :

• 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

• Lets take an example for better understanding

a = 10 b = 20

if a < b : T
a <= b : T
a>b : F
a >= b : F
a == b : F
a != b : T

• Lets take an example by using if … else

a = int ( input ( “ enter a number ) )


if a < 0 :
print ( “ Negative “ )
else :
print ( “ Positive “ )

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

. AND is like multiplication and it is useful to check the range of values

50 100

If x >= 50 and x <= 100

• Lets take an example about subjects (maths , phy , and chem ) where above 45 will be the passing
marks

if math>=45 and phy >=45 and chem >=45 :


print (“pass”)
else :
print (“ fail “)
• AND is use to check this type of conditions where everything must be true ( both conditions should be
true )

lii OR
• If the cond1 or cond2 both are false returns false
• OR is like addition

50 100

• OR is useful to check outside the range

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

• Anything written inside ‘ ’ , “ ” in quotes is called string


• String can contain english alphabet ,special characters like @ - \. / # ( ) , it can also
contain characters from other languages also
• In memory strings looks like an array of Character it has +ve and -ve indexing as well
• When you call an input function normally it'll give string by default
• len( ) gives you length of a string
• We can use for loop for accessing every element in a 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

How are you ’ ’ ’

or

“ “ “ hello

How are you ” ” ”

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)

Output : hello world

s5= 'hello' + 5

• # TypeError: can only concatenate str (not "int") to str

• We have to do type casting with string

S5 = 'HI'+str(5)

print (S5)

Output : HI5

Repetition
s1 = 'hi'

s1 * 3

Output : hihihi

But the thing is it should be integer

• You can have same string multiple times by using multiplication s1 * 2.5

S1= 'Hello'

S1*-2.5 # TypeError: can't multiply sequence by non-int of type 'float'

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= ‘hello world ‘


• s1[0 : len (s1) : 1 ]
• Output : hello w
s1 = 'hello world'

s1[0:len(s1):1]

s1= 'hello world'

>>>

s1[:len(s1):1]

O/p: 'hello world'

s1[::2]
O/p: 'hlowrd'

s1[3::]

O/p: 'lo world'

s1[6:8]

O/p: 'wo'

s1[::-1]

O/p: 'dlrow olleh'

s1[:-len(s1)-1:-1]

O/p: 'dlrow olleh'

s1[-1::-1]

O/p: 'dlrow olleh'

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

'H' in s1—— True

'ld' in s1—— True

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

Introduction to string methods


• The string is a built - in class in python
• Classes contains definition / design ( there are of 2 types data and operation / methods )
• Objects is an instance of that definition design
• In string many member function are available these member functions are called string methods
• To know all the methods present in string class we can type a function called dir( str ) it shows all the
method
• You can access all the methods using dot ( . ) operator (or) just want to know about particular
method

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 = “ hello , how are you “

This is how String is stored

• It has 18 characters and it is hold by a reference that is s

s.find ( sub [ , start [ ,end]])


• sub ( find the occurrence of the substring )
• Methods are called by using object name that is variable name
s.find(‘o’)
It will start looking for o from the left hand of the string .
O/P: 4

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

• You can pass the find by single , double or 3 parameters

Reverse String : s.rfind()

s.rfind ( sub [ , start [ ,end]])


• It is same as find but in find we where searching from left but in rfind will search substring from right

s.rfind(‘o’)

O/p: 16 (index value)

s.find (‘o ‘ , 0 , 15 )

O/p: 8 (index value)

• In rfind ending index will work but in find starting index will work

• -1 will return if its out of string

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( )

• s.index('o') -- O/p : 4

• It will count the number of occurrence Lets take an example - character ‘ o ‘

‘o’ it repeated 3 times

• The count gives counting of the string. It will not gives all the indexes . It will only count

s.find ( ‘ k ‘ )  O/p :-1

s.index (‘ k ‘ ) # error: substring not found

s.count('a') 1
s.count('H') 1
s.count(‘are’) 1

Adding and Removing Space

s.ljust(width[,fill])
s.rjust(width[,fill])
s.center(width[,fill])

• This methods are useful for text alignment

s = ‘ python ‘

• If you want to write in extra spaces like 10 spaces s.ljust ( )

s.rjust ( )
s.center ( )

s.center(10 , ‘ # ‘ )

• If the string is larger than the spaces given by using

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.rstrip - tailing removes character

s.strip - removes spaces from both the side

S = '...... ...... ++ PPpython'

s. lstrip (‘ . ‘ ) ———> it will remove leading dots and stops when there is no dot

O/p - ' ...... ++ PPpython'

s.lstrip(‘ . + ‘ ) ———> it will remove dot spaces and +

O/p - 'PPpython'

• All this methods will return new string they will generate new string after performing the operations

• The methods we are discussing here are

Changing Case

s.capitalize( )
s.lower( )
s.upper( )
s.title( )
s.swapcase( )
s.casefold( )

b='hI,how aRE yoU’

b.capitalize()

O/p: 'Hi,how are you'

b.lower()

O/p: 'hi,how are you'


b.upper()

O/p: 'HI,HOW ARE YOU'

b.swapcase()

O/p: 'Hi,HOW Are YOu'

b.title()

O/p: 'Hi,How Are You'

b.casefold()

O/p:'hi,how are you'

String Methods
s.isupper( )
s.islower( )
s.istitle ( )
s.isalnum ( )
s.isalpha ( )
s.isspace ( )
s.isascii ( )

• It will return in boolean result ( T or F )

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 ( )

s = ‘ How Are You ‘

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()

O/P: — — > False

S='abc123’

S.isalnum()

True

s.isalpha ( )

• If it is only alphabets then it will return true


• s = ‘ abcd ‘ ——> True
• s = ‘ abcd123’ — — > False
• W='Hello howareyou'-- Flase
This alpha and alpnum works on any language

s.isspace ( )

• It will check if there are any spaces present in the string then it will return true

s = ‘ hello world ‘ ——> 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 ——> True #empty string will return True

s.isidentifier( ) : This method will check if it gives the valid name of


the variable

s = ‘ length1 ‘

s.isidentifier() ——>O/p : True

s = ‘ 1length ‘ ——> False

Variable can not Start with a number so it will return false

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 = ‘ hello \n how are you ‘ ——> False


s.isdecimal( )

It will say of there are decimal present in the string

s = ‘ 125 ‘ ——> True

s = ‘ 1.25 ‘ ——>False

What are decimal ?? Decimal are the numbers between 0 - 9

s.isdigit( )

s = ‘ 1682 ‘ ——> True

• If you have special numbers it will return true •


But in s.isdecimal ( ) it will return False

s.isnumeric( )

s = ‘ 5 ‘ ——> True
1/2

• But in decimal and digit it will be false


• It will return true to any number

You might also like