Flow of Control
Flow of Control
Flow of Control
Introduction
The order of execution of the statements in a program is known as flow of control.
● for loop
● while loop
For Loop
A for loop allows you to repeat a block of code a specific number of times or
iterate over a sequence of values
Syntax
print(i) print(i)
1 1
2 3
3 5
5
1. Write a program to accept a number from user and print the multiple of the
number.
2. Write a program to print all odd numbers between 1 to 100.
3. Write a program to print the number and it square.
4. Python program to calculate the sum of all numbers from 1 to a given number.
5. Python program to check the number is prime or not.
6. Python program to display numbers from a list using a “for” loop.
Pyramid pattern of numbers
1 1
12 22
123 333
1234 4444
12345 55555
number = int(input("Enter the Number: "))
sum = 0
print(sum)
number = int(input("Enter the Number: "))
factorial = 1
factorial = factorial*i
A "while" loop is used when the number of iterations is unknown. The statement
repeats itself till the boolean value becomes false.
Syntax
while expression:
statement(s)
Example
count = 0
The count is: 0
while (count < 9): The count is: 1
The count is: 2
print 'The count is:', count The count is: 3
The count is: 4
count = count + 1
The count is: 5
The count is: 6
The count is: 7
print "Good bye!" The count is: 8
Good bye!
1. Program to print odd numbers from 1 to 10
2. Find the sum of even numbers using while loop
3. Write a program to reverse a number.
4. WAP to check whether the number is a palindrome or not.
5. WAP to check whether the string is Palindrome or not.
Loop Control Statements
i=1
while i < 6:
print(i) 1
if i == 3: 2
break 3
i += 1
We can stop the current iteration, and continue with the next:
i = 0
while i < 5: 1
i += 1 2
if i == 3: 4
continue
print(i)
The pass Statement
if n == 2:
pass 0 1 3 4
else:
print(n)
The else Clause
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
Python - Exceptions Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
These exceptions can be handled using the try and except statement:
The try block lets you test a block of code for errors.
except :