Python Track · Part 2 of 9

Python Control Flow: if, elif, else and Loops

Python
Control Flow
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

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 Statement
x = 10
if 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 Statement
x = 3
if 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 & else
x = -2
if 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 loop
for i in range(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 loop
x = 0
while 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 statement
for i in range(10):
    if i == 5:
        break
    print(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 statement

for i in range(5):
    if i == 2:
        continue
    print(i)
0
1
3
4

Citation

BibTeX citation:
@online{alekha2024,
  author = {Alekha, Gujuri},
  title = {Python {Control} {Flow:} If, Elif, Else and {Loops}},
  date = {2024-10-20},
  url = {https://gujurialekha.github.io/blog/python/02-python-control-flow.html},
  langid = {en}
}