Python

champak
₹2,000.00 ₹300.00
The Python Programming Language at Champak's World
  • 22 students
  • 41 lessons
  • 0 quizzes
  • 10 week duration

Python

Arithmetic Operations in Python

Python supports the following Arithmetic Operators.

+ plus
– minus
* multiplication
/division
% modulus
** exponent
// floor division

Precedence levels

()

**

*,  /, //, %

+,-

Operators at the same level are evaluated from left to right.

Out of these the last 4 require explanation.
Division / in Python is not integer division unlike languages like C, C++, Java etc.
Thus


print ("2/3=",2/3)
print ("3/2=",3/2)
print("4/2=",4/2);

This is the output

2/3= 0.6666666666666666
3/2= 1.5
4/2= 2.0
As you can see even 4/2 is shown as 2.0
Every value is converted to float and then divided
What happens in the case of division by 0 and 0/0

In both cases we get a division by zero error

ZeroDivisionError: division by zero

We will learn how to catch errors later on. At this point you need to remember that this error will stop your program at this point.

 

% modulus finds the remainder.

Python remainder works for float as well.
Thus 3.3 % 2.5 will give 0.8
-3.3%2.5 will give 1.7
-3.3 % -2.5 will be -0.8

If both numerator and denominator are +ve then you simply divide and get the remainder. Thus 10%3 is 1 because 10=3*3 +1

-10 % 3= -10 = -12 + 2. Thus answer is 2. Find the number just less than or equal to the numerator.

What is 10 % -3. 10. Calculate -10%3 and add a negative sign

-10%-3 will be same as 10%3 with a -ve sign

// integer division


print ("10%2.5=",-10%-3)
print ("10//3=",10//3)
print ("-10//3=",-10//3)
print ("10//-3=",10//-3)
print ("-10//-3=",-10//-3)

Output

10//3= 3
-10//3= -4
10//-3= -4
-10//-3= 3

** is the exponentiation operator.

2**3 =8
2**-3=1/8=0.125

3**1/2=(3**1)/2=3/2=1.5

3**(1/2)=square root of 3= 1.7320508075688772

-3**(1/2)=-1.7320508075688772

(-3)**(1/2)=1.0605752387249068e-16+1.7320508075688772j
Python supports complex numbers.

Assignments

Write expressions for

  1. Area of a triangle s(s-a)(s-b)(s-c). Hint use **
  2. Write expression for CI(Compound Interest)

Leave a Reply

Your email address will not be published. Required fields are marked *