Python Control Stuctures
Python Control Stuctures
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)
while statement
while statement continues repetition until the expression becomes false. The expression is a logical
expression and must return either True or False.
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.
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')
for n in range(2,num):
if num%n==0:
print('Not a prime number')
break
else:
print('Prime number')