Practice Examples on Operators in Python

In this class, we do some practice examples on operators in python.

For Complete YouTube Video: Click Here

Practice Examples on operators

To learn more about operator precedence and associativity click here.

Example 1:

print(11//2)

In the above example, it is doing floor division. the output is 5.

Example 2:

print(11.0//2)

In the above example even it is a floating number, floor division takes floor value. the output is 5.0.

Example 3:

print(-16//3)

The above example floor division on a negative number. floor division takes the least value. the output is -6.

Example 4:

i=1

print(i)

i++

print(i+1)

The above example doesn’t compile. There is no concept of i++ in python.

Example 5:

x=5

y=10

print(5**2>25 and y<50)

The above example power having the highest precedence so 5 power 2 is 25.

25>25 no False.

and y <50. Finally, we get False. because False and True is False.

Example 6:

Print(2+3-2*(6-8/2*4**2*2))

In the above expression, brackets have the highest precedence. so execute an expression in the bracket.

From the expression in inner brackets, power has the highest precedence.

4 power 2 is 16.

The remaining multiplication and division equal precedence so left to right associativity.

8/2=4

4*16*2=128

6-128=-122

Now coming out of the bracket we have 2*-122 = -244.

2+3- -244.

249.

Example 7:

Write a program to swap two numbers in python.

It’s very easy in python.

a=5

b=6

a,b=b,a.

By using the above assignment we can easily swap variables.