IKH

Operators

  • Operator is a symbol that performs certain operations.
  • Python provides the following set of operators;
    •  Arithmetic Operators
    • Relational Operators or Comparison Operators
    • Logical operators
    • Bitwise operators
    • Assignment operators
    • Special operators

Arithmetic Operators

  • + ⇒ Addition
  • – ⇒ Subtraction
  • * ⇒ Multiplication
  • / ⇒ Division operator
  • % ⇒ Modulo operator
  • // ⇒ Floor Division operator
  • ** ⇒ Exponent operator or power operator

Example

Python
num1 = 10
num2 = 2

print('num1+num2 =', num1+num2)
print('num1-num2 =', num1-num2)
print('num1*num2 =', num1*num2)
print('num1/num2 =', num1/num2)
print('num1//num2 =', num1//num2)
print('num1%num2 =', num1%num2)
print('num1**num2 =', num1**num2)

Output

PowerShell
num1+num2 = 12
num1-num2 = 8
num1*num2 = 20
num1/num2 = 5.0
num1//num2 = 5
num1%num2 = 0
num1**num2 = 100
Python
num1 = 10.5
num2 = 2

print('num1+num2 =', num1+num2)
print('num1-num2 =', num1-num2)
print('num1*num2 =', num1*num2)
print('num1/num2 =', num1/num2)
print('num1//num2 =', num1//num2)
print('num1%num2 =', num1%num2)
print('num1**num2 =', num1**num2)

Output

PowerShell
num1+num2 = 12.5
num1-num2 = 8.5
num1*num2 = 21.0
num1/num2 = 5.25
num1//num2 = 5.0
num1%num2 = 0.5
num1**num2 = 110.25

Remark

  • / operator always performs floating point arithmetic. Hence it will always returns float value.
  • Floor division (//) can perform both floating point and integral arithmetic. If arguments are int type then result is int type. If at least one argument is float type then result is float type.
  • We can use + and * operators for str type also.
    • + ⇒ String Concatenation Operator
    • * ⇒ String Multiplication Operator
  • If we want to use + operator for str type then compulsory both arguments should be str type only otherwise we will get error.

Example

Python
str1 = "ajay"
print(str1 + 10)

Output

PowerShell
TypeError: can only concatenate str (not "int") to str
  • If we use * operator for str type then compulsory one argument should be int and other argument should be str type.
Python
str1 = "ajay"
print(str1*2)
print(2*str1)
print(2.5*str1)
print(str1*"ajay")

Output

PowerShell
ajayajay
ajayajay
TypeError: can't multiply sequence by non-int of type 'float'
TypeError: can't multiply sequence by non-int of type 'str'

Remark

  • For any number x, x/0 and x%0 always raises “ZeroDivisionError”. Example 10/0, 10.0/0 … etc.

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error