Python Control Statements Lesson003 (1)
Python Control Statements Lesson003 (1)
1. if statement
2. if else statement
3. Ladder if else statement (if-elif-else)
4. Nested if statement
Python If statements
This construct of python program consist of one if condition with one block
of statements. When condition becomes true then executes the block given
below it.
Syntax:
if ( condition):
…………………..
…………………..
…………………..
Flow Chart: it is a graphical
representation of steps an
Flowchart algorithm to solve a problem.
Example:
Age=int(input(“Enter Age: “)) If
( age>=18):
Print(“You are eligible for vote”)
If(age<0):
Print(“You entered Negative Number”)
Flowchart
Example-1:
Age=int(input(“Enter Age: “))
if ( age>=18):
print(“You are eligible for vote”) else:
print(“You are not eligible for vote”)
Example-2:
Syntax:
if ( condition-1):
…………………..
………………….. elif
(condition-2):
…………………..
…………………..
elif (condition-3):
…………………..
…………………..
else:
…………………..
…………………..
Example:
num=int(input(“Enter
Number: “)) If
( num>=0):
Print(“You entered positive number”) elif
( num<0):
Print(“You entered Negative number”) else:
Print(“You entered Zero ”)
Python Nested if statements
It is the construct where one if condition take part inside of other if condition.
This construct consist of more than one if condition. Block executes when
condition becomes false and next condition evaluates when first condition
became true.
So, it is also multi-decision making construct.
Syntax: FlowChart
if ( condition-1):
if (condition-2):
……………
……………
else:
……………
……………
else:
…………………..
…………………..
Example:
num=int(input(“Enter Number:
“)) If ( num<=0): if ( num<0):
Print(“You entered Negative number”)
else:
Print(“You entered Zero ”)
else:
Print(“You entered Positive number”)
Python Iteration Statements
The iteration (Looping) constructs mean to execute the block of statements
again and again depending upon the result of condition. This repetition of
statements continues till condition meets True result. As soon as condition
meets false result, the iteration stops.
Python supports following types of iteration statements
1. while
2. for
WHILE LOOP in Python
Definition:
A while loop in Python executes a block of code as long as a specified condition is
True. It checks the condition before each iteration.
Syntax:
while condition:
# code block to execute
Use indentation (typically 4 spaces) instead of braces {} like in JavaScript.
Flow:
1. Evaluate condition
2. If True, run the indented block
3. Repeat step 1
4. If False, exit the loop
Example:
i=0
while i < 5:
print("Number is:", i)
i += 1
Explanation:
Starts with i = 0
Prints numbers 0 through 4
Stops when i becomes 5
Common mistake:
If you forget i += 1, it causes an infinite loop.
Use Cases:
Reading user input until valid
Waiting for a specific event
Repeating tasks until a condition is met