PWP - Chapter 2
PWP - Chapter 2
PWP - Chapter 2
Arithmetic Operators-
/ Division e.g. x / y
% Modulus e.g. (x % y)
• The truncating division operator (//, also known as floor division) truncates
the result to an integer and works with both integers and floating-point
numbers.
• In Python 2, the true division operator (/) also truncates the result to an
integer if the operands are integers.
• x == y Equal to
• x != y Not equal to
w<x<y<z
• Expressions such as x < y > z are legal but are likely to confuse anyone
reading the code (it’s important to note that no comparison is made between
x and z in such an expression). Comparisons involving complex numbers
are undefined and result in a TypeError.
• Operations involving numbers are valid only if the operands are of the
same type.
Assignment Operators-
It is equivalent to a = a + 5.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Logical Operators-
Vishal Chavre
Logical Operators in Python
x = True
y = False
# Output: x or y is True
print('x or y is', x or y)
Bitwise Operators-
>>> x = 1 # 0001
• In the first expression, a binary 1 (in base 2, 0001) is shifted left two slots to
create a binary 4 (0100). The last two operations perform a binary OR
(0001|0010 = 0011) and a binary AND (0001&0001 = 0001). Such bit-
masking operations allow us to encode multiple flags and other values
within a single integer.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)
Membership :
• in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
Vishal Chavre
• In a dictionary we can only test for presence of key, not the value.
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Vishal Chavre
• When you create an instance of a class, the type of hat instance is the class
itself. To test for membership in a class, use the built-in function
isinstance(obj,cname)
• This function returns True if an object, obj, belongs to the class cname or
any class derived from cname.
example:
example:
Identity Operators:-
• is and is not are the identity operators in Python. They are used to check if
two values (or variables) are located on the same part of the memory. Two
variables that are equal does not imply that they are identical.
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
• Here, we see that x1 and y1 are integers of same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).
• But x3 and y3 are list. They are equal but not identical. It is
because interpreter locates them separately in memory although they are
equal.
• s.attr Attributes
modulo
• x + y, x - y Addition, subtraction
• x|y Bitwise or
• x or y Logical or
Control Flow:-
Conditional Statements
• The if, else, and elif statements control conditional code execution.
If Statement:
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only
if the text expression is True.
If the text expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. Body starts
with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.
num = 3
if num > 0:
num = -1
if num > 0:
Output:
3 is a positive number.
if...else Statement
Syntax
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only
when test condition is True.
If the condition is False, body of else is executed. Indentation is used to separate
the blocks.
Example of if...else
# Program checks if the number is positive or negative
num = 3
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
Vishal Chavre
print("Negative number")
Output:
Positive or Zero
In the above example, when num is equal to 3, the test expression is true and body
of if is executed and body of else is skipped.
If num is equal to -5, the test expression is false and body of else is executed and
body of if is skipped.
If num is equal to 0, the test expression is true and body of if is executed
and body of else is skipped.
Syntax of if...elif...else
if test expression:
Body of if
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False , it checks the condition of the next elif block and so on.
If all the conditions are False , body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif...else
Example of if...elif...else
# In this program,
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output:
Positive number
We can have a if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. This can get confusing, so must be avoided
if we can.
Python Nested if Example
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
Vishal Chavre
Looping in Python:
For Loop:
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop
Body of for
Here, val is the variable that takes the value of the item inside the sequence on
each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
# List of numbers
sum = 0
sum = sum+val
Output:
The sum is 48
To force this function to output all the items, we can use the function list().
The following example will clarify this.
print(range(10))
Vishal Chavre
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
We can use the range() function in for loops to iterate through a sequence of
numbers. It can be combined with the len() function to iterate though a sequence
using indexing. Here is an example.
# Program to iterate through a list using indexing
for i in range(len(genre)):
I like pop
I like rock
I like jazz
A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is
ignored.
for i in digits:
print(i)
else:
Output:
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop
exhausts, it executes the block of code in the else and prints.
Output:
No items left.
while loop:
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
We generally use this loop when we don't know beforehand, the number of times
to iterate.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only
if the test_expression evaluates to True. After one iteration, the test expression is
checked again. This process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
Flowchart of while Loop
Vishal Chavre
# numbers upto
# sum = 1+2+3+...+n
# n = int(input("Enter n: "))
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
Output:
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter
variable i is less than or equal to n (10 in our program).
We need to increase the value of counter variable in the body of the loop. This is
very important (and mostly forgotten). Failing to do so will result in an infinite
loop (never ending loop).
Same as that of for loop, we can have an optional else block with while loop as
well.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such case,
the else part is ignored. Hence, a while loop's else part runs if no break occurs and
the condition is false.
Example:
# Example to illustrate
counter = 0
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Output:
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three times.
On the forth iteration, the condition in while becomes False. Hence, the else part is
executed.
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until test expression is false, but sometimes we
wish to terminate the current iteration or even the whole loop without checking test
expression.
The break statement terminates the loop containing it. Control of the program
flows to the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Syntax of break
break
Flowchart of break
The working of break statement in for loop and while loop is shown below.
Example:
# Use of break statement inside loop
if val == "i":
break
print(val)
print("The end")
Output:
s
t
r
The end
In this program, we iterate through the "string" sequence. We check if the letter
is "i", upon which we break from the loop. Hence, we see in our output that all the
letters up till "i" gets printed. After that, the loop terminates.
Python continue statement
The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.
Syntax of Continue
continue
Flowchart of continue
The working of continue statement in for and while loop is shown below.
Example:
if val == "i":
continue
print(val)
print("The end")
Output:
s
t
r
n
g
The end
We continue with the loop, if the string is "i", not executing the rest of the block.
Hence, we see in our output that all the letters except "i" gets printed.
pass statement:
Syntax of pass
pass
Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.
Example:
pass
def function(args):
pass
class example:
pass
Programs based on Concept in chapter 2:
num1 = 1.5
num2 = 6.3
Output:-
Output:-
Vishal Chavre
Python Program to calculate the square root
Input:
Output:
Output:-
Output:-
year = 2000
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output:-
Output:-
factorial = 1
Output:-
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
Python Program to convert temperature in celsius to fahrenheit
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
Output:-
Output:-
Enter a number: 43
43 is Odd
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
Output:-
Output:-
num = 7
Output:-
Vishal Chavre
Vishal Chavre