Learn how Python makes decisions and repeats work with if, elif and else statements, for and while loops, and break and continue.
Author
Gujuri Alekha
Published
Oct 20, 2024
Python, control flow statements are used to manage the flow of a program’s execution. They allow you to make decisions, loop through code, and modify the program’s behavior based on conditions.
2.1 Conditional Statements (if, elif, else)
Conditional statements are used to execute different blocks of code based on whether a specific condition is true or false.
2.1.1 “IF” Condition
The if statement is used to check a condition. If the condition is true, the code inside the if block is executed.
Show code
# if Statementx =10if x >5:print("x is greater than 5")
x is greater than 5
2.1.2 “elif” (short for “else if”)
The elif statement is used to check additional conditions if the previous if or elif conditions are not met. You can have multiple elif blocks.
Show code
# Else Statementx =3if x >5:print("x is greater than 5")elif x >0:print("x is positive but not greater than 5")
x is positive but not greater than 5
Show code
# else & elsex =-2if x >5:print("x is greater than 5")elif x >0:print("x is positive but not greater than 5")else:print("x is non-positive")
x is non-positive
2.2 Loops (for, while)
Loops allow you to repeat a block of code multiple times. In Python, two common types of loops are the for loop and the while loop.
2.2.1 “for” Loop
It is used to iterate over a sequence (like a list or a range) or any iterable object. The loop executes a specified block of code for each item in the sequence.
Show code
# for loopfor i inrange(5):print(i)
0
1
2
3
4
2.2.2 “while” Loop
It is used to repeatedly execute a block of code as long as a specified condition is true.
Show code
# while loopx =0while x <5:print(x) x +=1
0
1
2
3
4
Show code
# Iterating Through Data Structures:my_list = [1, 2, 3, 4, 5]for item in my_list:print(item)
1
2
3
4
5
2.3 Break and Continue Statements
break : The break statement is used to exit a loop prematurely. It is often used in conjunction with conditional statements to terminate a loop based on a specific condition.
Show code
# Break statementfor i inrange(10):if i ==5:breakprint(i)
0
1
2
3
4
continue : The continue statement is used to skip the current iteration of a loop and move to the next iteration.
Show code
# continue statementfor i inrange(5):if i ==2:continueprint(i)
0
1
3
4
Get new notebooks as they're published
New parts are added to each track in order. Follow along: