Control Structures in Python
1. Selection control structure
if statement
if statement contains a logical expression and if the result is True if block is executed.
Syntax
if expression:
statement(s)
else Statement
An else statement is combined with an if statement. And contains the block of code that executes if the
expression in the if statement resolves to 0 or a False value.
Syntax
if expression:
statement(s)
else:
statement(s)
elif Statement
allows to check multiple expressions for truth value. There can be an arbitrary number of elif statements
following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
else:
statement(s)
nested if statement
Syntax
if expression1:
if expression2:
statement(s)
else:
statement(s)
else:
statement(s)
2. Repetition control structure (Loop statements)
while statement
for statement
while statement
while statement continues repetition until the expression becomes false. The expression is a logical
expression and must return either True or False.
1 Prepared by Sisira Palihakkara
Syntax
while expression:
statement(s)
for Loop Statement
for loop in Python can iterate over the items of any sequence, such as a list , a string , a tuple or a range object.
Syntax
for iteratingVar in sequence:
statement(s)
The sequence is evaluated first. Then, the first item in the sequence is assigned to the iterating variable -
iteratingVar. Next, the statements block is executed. Each item in the list is assigned to iteratingVar, and the
statements block is executed until the entire sequence is exhausted.
break Statement
break statement in Python terminates the current loop and resumes execution at the next statement.
The break statement can be used in both while and for loops.
continue Statement
continue statement rejects all the remaining statements in the current iteration of the loop and moves the
control back to the top of the loop.
continue statement can be used in both while and for loops.
else Statement with while loops
If the else statement is used with a while loop, the else statement is executed when the condition becomes
false.
Syntax
while expression:
statement(s)
else:
statement(s)
If the else statement is used with a for loop, the else statement is executed when the loop has exhausted
iterating the list.
num=int(input('Enter a number: '))
while num<=0:
num=int(input('Enter a number: '))
n=2
while n<num:
if num%n==0:
print(num, 'is not a prime number')
break
n+=1
else:
print(num,'is a prime number')
2 Prepared by Sisira Palihakkara
else Statement with for loop
else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating
the sequence.
If the break statement is executed else statement is not executed.
num=int(input('Enter a number: '))
while num<=1:
num=int(input('Enter a number: '))
for n in range(2,num):
if num%n==0:
print('Not a prime number')
break
else:
print('Prime number')
3 Prepared by Sisira Palihakkara