Control Structures
Control Structures
Program:
Num1=eval(input(‘enter first number’))
Num1=eval(input(‘enter first number’))
if Num1>Num2:
print(Num1, ‘is greater than’, Num2)
else:
print(Num2, ‘is greater than’, Num1)
If-else statement…..point to remember
(a) Indentation is very important in Python. The else keyword must be
properly lined up with the if statement.
(b) In case the if and the else keywords are not in same column, then
Python will not know that if and else will go together and it will
show indentation error.
If-else statement-Example
Write a program to test whether a number is divisible by 5 and 10 or
by 5 or 10
Num1=eval(input(‘enter a number’))
if (Num1%5==0 and Num1%10==0):
print(Num1, ‘is divisible by both 5 and 10’)
if(Num1%5==0 or Num1%10==0):
print(Num1, ‘is divisible by 5 or 10’)
else:
print(Num1, ‘is divisible not by 5 and 10’)
Nested If statement
We can have a if-else statement inside another if-else
statement. This is called nesting in computer programming.
Any number of these statements can be nested inside one
another. Indentation is the only way to figure out the level of
nesting.
Syntax: In this syntax, if Boolean
if Boolean_expression1: expression 1 and Boolean expression
if Boolean_expression2: 2 are correct then statement 1 will
execute. If Boolean expression 1 is
Statement1 correct but Boolean expression 2 is
else: incorrect, statement 2 will
Statement2
execute. And if both Boolean
expression 1 and Boolean expression
else: 2 are false then statement 3 will
Statement3 execute.
Program to demonstrate Nested If statement
x = float(input("Enter a number: "))
if x >= 0:
if x== 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Python Multiway if...elif..else Statement
The elif is short for else if. It allows us to check for multiple expressions. If the
condition for if is false, it checks the condition of the next elif block and so on.
If all the conditions are false, the body of else is executed. Only one block
among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.