Python Operators

In every language we come across a series of operators which are playing a significant part in all known structures, mathematical relationships or estimations. When you want to check, validate, compare or relate some variables or statements, or to solve complex mathematical formulas, you use operators. There are different kinds of operators. We have the numerical operators and the comparing operators.

Numerical Operators

  1. +, -, /, *, %, ** etc.
  2. (+) Standard addition
  3. (-) Standard subtraction
  4. (/) Standard Division
  5. (*) Standard Mutliplication
  6. (%) Modulus (A division which spits the remainder)
      (Can be used for string formatting)
  7. (**2) Power of 2, (**3) Power of 3, (**4) Power of 4...etc
Examples using IDLE of Python. Try to write your own operations. You can solve either long expressions with parenthesis, like "(23*3) - (23%2) ** 3.42" or simple tasks like showed below. Don't just read them. Implement them as well! You learn python by trial and error. Repetition.

>>>  5000 + 5000
10000
>>>  300 - 200
100

"""So far you must be feeling quite comfortable with the IDLE. Use it a lot."""

>>>  100 / 2
50

"""It is a really powerful asset when developing your own scripts. An by the way this is a comment."""

>>>  400 * 3
1200
>>>  300 % 200
100
>>>  40 ** 2
1600

exercise-icon Try it!

Type the following expression (34 + (98.2%2) / 87)**2 (Don't mind extra or no spaces).
?

Other Operators

  1. = (Assigns the right side to the left side {variable} )
  2. ! (This operator is an equivalent of the word NOT)
  3. == (Checks whether the left side is equal to the right side by value)
  4. != (Left side NOT EQUAL the right side)
  5. & (Left side AND right side)
  6. > (Left side GREATER than right side)
  7. >= (Left side GREATER OR EQUAL than right side)
  8. < (Left side SMALLER than right side)
  9. <= (Left side SMALLER OR EQUAL than right side)
  10. | (Left side applies OR right side applies)


>>>  a = 2
>>>  if (a != 3):
        print 'Not Equal'

'Not Equal'
>>>  b = 4
>>>  if (a & b) > 0:
        print "Positive"

'Positive'
>>>  if (a <= b):
        print "A is smaller"

'A is smaller'
>>>  if (b >= a):
        print "B is greater"

'B is greater'
>>>  a < b
True
>>>  a > b
False
>>>   a = 3
>>>   b = 2
>>>   if (a | b) > 0:
        print a
3

exercise-icon Try it!

Assume firstNum = 23 and a second variable named secondNum = 29. Write the corresponding command which describes that firstNum is LESS OR EQUAL than secondNum. Don't use the "if" statement from above. Only the variables and the relation.

?

exercise-icon Pop Quiz

Assume variables numOne = 23.6456 and numTwo = 931. Write the corresponding command which states the modulus division of these two variables.

Set numOne to the second (2) power.

Write the proper comparing command to check whether value of numOne is EQUAL to the value of numTwo.

Print to the screen the string "This test is way to easy dude!".


?