Operators

PYTHON OPERATORS

Like all computer programming languages, python also supports following basic operators. Using these operators, we can perform mathematical operations on variables.

Basic operators in Python


+ for addition operation
-  for subtraction operation
*  for multiplication operation
/  for division operation
%  for modulus operation
**  for exponent operation
//  for floor division operation

Examples of Python Operators


Let’s use these operators on following two variables:
num1 = 10
num2 = 5

Addition
num1 + num2 will result in 15

Subtraction
num1 - num2 will result in 5

Multiplication
num1 * num2 will result in 50

Division
num1 / num2 will result in 2

Floor Division

num1 // num2 will result in 2 (rounds down the answer to the nearest whole number)

Modulus

num1 % num2  will result in 0 (It’s remainder of 10 divided by 5)

Exponent

num1 ** num2  will result in 100000 (10 to the power of 5)

Assignment Operator (=)


Like most of the programming languages, Python uses equal sign (=) as assignment operator.


number = 5

Above statement will assign value 5 to variable number.

There are a few more ways to use assignment operators in Python; examples are +=, -= and *=.

If we want to increment value of number by 2, we can write

number = number + 2

Python will first evaluate the expression on the right side i.e. number + 2 and assign the answer to the left side. Hence execution of above statement will result in number = 7 (assuming initial value of number is 5).

The same statement can also be written as under:

number += 2

The number += 2 is actually a short form of the statement number = number + 2

Similarly, if we want to do a subtraction, we can write number = number – 2 or number -= 2. The same works for most of the python operators described above.

* * * * *


<  Back to Home Page >



No comments:

Post a Comment