Learn Core Python

Arithmetic Operators

Arithmetic Operators:-

+  --> Addition

-  --> Subtraction

*  --> Multiplication

/  --> Division

%  --> Modulo Division

// --> Floor Division

** --> Exponent Operator or power Operator

 

E.g1:-

a = 10
b = 2
print(a+b) # 12
print(a-b) # 8
print(a*b) #20
print(a/b) #5.0
print(a%b) # 0
print(a//b) #5
print(a**b) #100

O/P:-

12

8

20

5.0

0

5

100

 

E.g:-

a = 10.5
b = 2
print(a+b) # 12.5
print(a-b) # 8.5
print(a*b) #21.0
print(a/b) #5.25
print(a%b) # 0.5
print(a//b) #5.0
print(a**b) #110.25

O/P:-

12.5

8.5

21.0

5.25

0.5

5.0

110.25

 

Note1:- /(division) operator always performs floating point arithmetic. SO it returns floating point value as result.

 

Note2:- //(division) It performs both floating point and integer arithmetic.

it performs integer arithmetic when both values are integer

it performs floating point arithmetic at least one value is floating point.

 

Note3:- We can use +,* operators on 'str' types also.

 

à If we want use '+' operator on 'strings' then both values should be string only otherwise

    we will get error. we call this operation is a "concatenation" operation.

E.g1:-

s1 = "akkem "
s2 = "sreenivasulu"
print(s1+s2) # akkem sreenivasulu

 

E.g2:-

s1 = "cfamily"
s2 = 10
print(s1+s2)

O/P:-

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

 

E.g3:- how to resolve above issue

way1:

s1 = "cfamily"
s2 = 10
print(s1+str(s2)) #cfamily10

 

E.g4:-

print('akkem '+"sreenivasulu") #akkem sreenivasulu

 

à If we use '*' operator on string values -- one value should be int and other value should

    be string.

E.g:-   

'cfamily'*2
'cfamily'*2
10*'cfamily'
print("*"*10)
print("+"*20)

 

'akkem '*'sreenivasulu' --> TypeError: can't multiply sequence by non-int of type 'str'

 

Important Notes:

On String values

à+ ==> String Concatenation Operator

à * ==> String Multiplication Operator

  

For any number x, x/0 and x%0 always raises "ZeroDivisionError".

10/0  --> ZeroDivisionError: division by zero

10%0  --> ZeroDivisionError: integer division or modulo by zero