Ch 2 Python Decision making and Loops:
• Write conditional statements using If statement, if ...else
statement, elif statement and Boolean expressions, While
loop, For loop, Nested Loop, Infinite loop, Break
statement, Continue statement, Pass statement, Use for
and while loops along with useful built-in functions to
iterate over and manipulate lists, sets, and dictionaries.
Plotting data, Programs using decision making and loops.
If statement
• Decision making is required when we want to execute a
code only if a certain condition is satisfied.
• Python if Statement Syntax
• if test expression:
• statement(s)
program
# If the number is positive, we print an appropriate
message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num < 0:
print(num, "is a negative number.")
print("This is also always printed.")
• Python if...else Statement
if test expression:
Body of if
else:
Body of else
program
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Python if...elif...else Statement
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
program
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
• Python Nested if Example
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
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.
• Syntax of while Loop
while test_expression:
Body of while
# Program to add numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
• 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
for val in sequence:
Loop body
for i in range(initialValue, endValue):
Loop body
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
Nested loop
• Python can be nested i.e. we can use one or more loops inside
another loop.
for in n:
# piece of code goes here
for in n:
# piece of code goes here
for i in range(1, 6):
# outer loop
for j in range(i):
# 1st level inner loop
print(i, end=“”)
print('\n')
break and continue statement
• In Python, break and continue statements can alter the
flow of a normal loop.
• break statement
• The break statement terminates the loop containing it.
Control of the program flows to the statement immediately
after the body of the loop.
# Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
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.
# Program to show the use of continue statement inside
loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Pass statement
• In Python programming, the pass statement is a null
statement.
• nothing happens when the pass is executed. It results in
no operation (NOP).
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
Infinite loop
i= 0
while i<=10:
print(i)
Program to find factorial
#Taking user input
n = int(input("Enter a number: "))
factorial = 1
if n < 0: #Check if the number is negative
print("Factors do not exist for negative numbers.")
elif n == 0: #Check if the number is zero
print("The factorial of 0 is 1.")
else:
for i in range(1,n + 1):
factorial = factorial*i
print("The factorial of",n,"is",factorial)
Program to check if year is leap year
#Remove comments from the bottom line to take input from the user
year = int(input("Enter a year: "))
#It is a centenary year if the value is divisible by 100 with no remainder.
#Centenary year is a leap year divided by 400
if (year % 400 == 0) and (year % 100 == 0):
print(year,”is a leap year")
#If it is not divisible by 100 then it is not a centenary year
#A year divisible by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year.".format(year))
#If the Year is not divisible by both 400 (centenary year) and 4 (centenary year)
then:
#The Year is not a leap year
else:
print("{0} is not a leap year.".format(year))
dictionary
• Python dictionary is an unordered collection of items.
Each item of a dictionary has a key/value pair.
• Creating a dictionary is as simple as placing items inside
curly braces { } separated by commas.
• An item has a key and a corresponding value that is
expressed as a pair key: value
Ploting data
• Matplotlib is a cross-platform, data visualization and graphical
plotting library for Python and its numerical extension NumPy.
• Matplotlib is a library for data visualization, typically in the form
of plots, graphs and charts.
• The easiest way to install matplotlib is to use pip.
• Package Installer for Python (pip) is the de facto and
recommended package-management system written in Python
and is used to install and manage software packages.
• Type following command in terminal:
• pip install matplotlib
# importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [100,200,300]
# corresponding y axis values
y = [5,8,12]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('voltage')
# naming the y axis
plt.ylabel('current’)
#giving title to graph
plt.title(" V I Chara")
#function to show graph
plt.show()
import pylab
# x axis values
x = [100,200,300]
# corresponding y axis values
y = [5,8,12]
# plotting the points
pylab.plot(x, y)
pylab.show()