Python Programming For Polytechnic-28!7!24 To 3-8-24
Python Programming For Polytechnic-28!7!24 To 3-8-24
Apart from sequential control flow statements you can employ decision making and looping control
flow statements to break up the flow of execution thus enabling your program to conditionally
execute particular blocks of code. The term control flow details the direction the program takes.
Sequential Control Flow Statements: This refers to the line by line execution, in which the
statements are executed sequentially, in the same order in which they appear in the program.
Decision Control Flow Statements: Depending on whether a condition is True or False, the decision
structure may skip the execution of an entire block of statements or even execute one block of
statements instead of other (if, if…else and if…elif…else).
Loop Control Flow Statements: This is a control structure that allows the execution of a block of
statements multiple times until a loop termination condition is met ( for loop and while loop). Loop
Control Flow Statements are also called Repetition statements or Iteration statements.
Program 3.1: Program Reads a Number and Prints a Message If It Is Positive
number = int(input("Enter a number"))
if number >= 0:
print(f"The number entered by the user is a positive number")
Program 3.2: Program to Read Luggage Weight and Charge the Tax Accordingly
weight = int(input("How many pounds does your suitcase weigh?"))
if weight > 50:
print(f"There is a $25 surcharge for heavy luggage")
print(f"Thank you")
The if…else Decision Control Flow Statement
An if statement can also be followed by an else statement which is optional. An else statement does
not have any condition. Statements in the if block are executed if the Boolean_Expression is True.
Use the optional else block to execute statements if the Boolean_Expression is False. The if…else
statement allows for a two-way decision.
1
Program 3.4: Program to Find the Greater of Two Numbers
number_1 = int(input("Enter the first number"))
number_2 = int(input("Enter the second number"))
if number_1 > number_2:
print(f"{number_1} is greater than {number_2}")
else:
print(f"{number_2} is greater than {number_1}")
This if…elif…else decision control statement is executed as follows:
In the case of multiple Boolean expressions, only the first logical Boolean expression
which evaluates to True will be executed.
n=0
while True:
print(f"The latest value of n is {n}")
n=n+1
if n > 5:
print(f"The value of n is greater than 5")
break
Write a Program to Check Whether a Number Is Prime or Not
number = int(input('Enter a number > 1: '))
prime = True
for i in range(2, number):
if number % i == 0:
prime = False
break
if prime:
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Program to Demonstrate continue Statement
n = 10
while n > 0:
print(f"The current value of number is {n}")
if n == 5:
print(f"Breaking at {n}")
n = 10
continue
n=n–1