Chapter One: Arithmetic Operations, Decisions and Looping
Chapter One: Arithmetic Operations, Decisions and Looping
• 8//5 = 1
• sum,avg = a+b+c,(a+b+c)/3
Arithmetic operations
Finding the data type
c=19
print ('19 in octal is %o and in hex is %x' %(c,c))
Output: 19 in octal is 23 and in hex is 13
Arithmetic operations
Coercion
• If operands that are of different data types are computed then coercion takes place
• Python converts operand with the “smaller” type to the “larger” type
• Coercion is also called casting
• Implicit coercion/casting done automatically when compiler is assured there wont
be data loss
• Explicit coercion/casting requires some code to be written so that there is no data
loss. E.g
num1,num2 = 15,”30”
ans = num1 + int(num2) # num2 cast from string to integer
• Can also use str ()to cast to string and float () to cast to a float etc
Arithmetic operations
Bitwise operations
• Operate on binary digits and can only be applied to integers and long integers
• x<<y (binary shift left): Returns x with bits shifted to the left by y places
• x>>y (binary shift right): Returns x with bits shifted to the right by y places
• x ^ y bitwise exclusive AND): Returns 0 if corresponding bits are the same otherwise it
returns a 1
Example:
a,b = 8.5,5.1
Math.trunc (a) returns 8
round (a) returns 9
math.floor (b) returns 5
math.ceil (a) returns 9
Arithmetic operations
Comparison operators
• A summary of the comparison operators
Example:
a,b = 7,8.8
a == b returns False
a is != b returns True
a is b returns False
a is not b returns True
Arithmetic operations
Comparison operators
• A summary of the comparison operators
Example:
a,b = 7,8.8
a == b returns False
a is != b returns True
a is b returns False
a is not b returns True
Making decisions
If…else statement
• Is the statement that helps in making decisions and controls program flow
• determines which block of statements to execute on the basis of the logical
expression included
• a block of statements is attached with if as well as with else, and when the logical
expression is evaluated, either the if or the else block statement is executed.
• Syntax:
if (logical expression):
statement(s)
else:
statement(s)
Making decisions
If…else statement
Example
i=16
if (i == 15)
print (‘i is equal to 15 ’)
Else:
print (‘i is not equal to 15 ’)
k=1
While k <=10 :
print (k)
k=k+1
Output: 1
.
.
.
10
Looping
The break statement
• The break statement terminates and exits from the current loop and resumes
execution of the program from the statement following the loop.
k=1
while 1 :
print (k)
k=k+1
if(k>10):
break
Output: 1
.
4
6
.
10
Looping
The continue statement
• range (x): Returns a list whose items are consecutive integers from 0
(included) to x (excluded)
• range(x, y): Returns a list whose items are consecutive integers from x (included)
to y (excluded). The result is an empty list if x is greater than or equal to y.
Output:
Random number is 4
Random number is 1
Notes