Python Control Flow: if, elif, else, and Loops

Python Control Flow: if, elif, else, and Loops Thumbnail

Python Control Flow: if, elif, else, and Loops

When you start learning Python, writing statements one after another is easy. But real programs need to make decisions and repeat certain tasks. For example, a program may need to check whether a student has passed, display a different message based on a user's choice, or repeat an operation several times.

This is where control flow becomes important.

In this tutorial, we will learn Python control flow from the beginning. We will cover if, elif, else, while, for, range(), break, continue, and pass with simple examples.

What Is Control Flow in Python?

Control flow describes the order in which Python executes statements in a program.

Normally, Python executes code from top to bottom. Control flow statements allow us to change that behavior by making decisions or repeating a section of code.

For example:

age = 20

if age >= 18:
    print("You are an adult.")

Here, Python checks the condition before deciding whether the print() statement should run.

Why Is Control Flow Important?

Almost every useful Python program needs some form of decision-making or repetition.

Control flow can help you:

  • Make decisions based on conditions
  • Validate user input
  • Repeat an operation
  • Stop a loop when a condition is met
  • Skip particular iterations
  • Build interactive programs
  • Control how different parts of an application execute

1. Python if Statement

The if statement is used when you want Python to execute code only when a condition is true.

Basic Syntax

if condition:
    # code to execute

Python uses indentation to identify the code belonging to the if block.

Example

temperature = 35

if temperature > 30:
    print("It is a hot day.")

Since 35 > 30 is true, Python prints the message.

Understanding Indentation

Indentation is an important part of Python syntax. Unlike some programming languages that use braces to define blocks, Python normally uses indentation.

age = 22

if age >= 18:
    print("Eligible")
    print("Condition is true")

Both print() statements belong to the if block because they are indented.

Incorrect indentation can cause an error, so keep the indentation consistent. Four spaces are commonly used.

2. Python if-else Statement

Sometimes you need one action when a condition is true and another action when it is false. The if-else statement is useful in this situation.

Example

marks = 42

if marks >= 40:
    print("Pass")
else:
    print("Fail")

If the marks are 40 or above, the first message is displayed. Otherwise, Python executes the else block.

3. Python if-elif-else

When there are several possible conditions, you can use elif.

Example

marks = 78

if marks >= 90:
    print("Grade A+")
elif marks >= 75:
    print("Grade A")
elif marks >= 60:
    print("Grade B")
elif marks >= 40:
    print("Grade C")
else:
    print("Fail")

Python checks the conditions from top to bottom. Once it finds a true condition, it executes that block and skips the remaining elif and else blocks.

4. Nested if Statements

An if statement can be placed inside another if statement. This is called a nested if.

Example

age = 22
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID is required")
else:
    print("Entry not allowed")

Nested conditions can be useful, but deeply nested code can become difficult to read. When possible, keep conditions simple.

5. Comparison Operators in Conditions

Conditions often use comparison operators.

Operator Meaning
== Equal to
!=
Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to

Example

number = 10

if number == 10:
    print("The number is 10")

6. Using and, or, and not

Python provides logical operators for combining conditions.

Using and

The and operator requires both conditions to be true.

age = 25
has_ticket = True

if age >= 18 and has_ticket:
    print("You can enter.")

Using or

The or operator returns a true result when at least one condition is true.

day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It is the weekend.")

Using not

The not operator reverses a Boolean condition.

logged_in = False

if not logged_in:
    print("Please log in.")

7. Python while Loop

A while loop repeats code as long as its condition remains true.

Basic Syntax

while condition:
    # code to repeat

Example

count = 1

while count <= 5:
    print(count)
    count += 1

The output is:

1
2
3
4
5

The variable count is increased after each iteration. Without updating the condition-related variable, you may accidentally create an infinite loop.

8. Infinite while Loop

An infinite loop continues running because its condition never becomes false.

For example:

while True:
    print("Running...")

This loop will continue until something stops it. A break statement can be used when you intentionally need to exit such a loop.

9. Python for Loop

The for loop is commonly used to iterate over items in a sequence or another iterable object.

Example with a List

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)

Python takes each item from the list and assigns it to fruit during each iteration.

10. for Loop with a String

You can also iterate over the characters of a string.

word = "Python"

for letter in word:
    print(letter)

This prints each character on a separate line.

11. The range() Function

The range() function is frequently used with for loops when you need a sequence of numbers.

Example

for number in range(5):
    print(number)

The output is:

0
1
2
3
4

Notice that range(5) starts at zero and stops before five.

Specifying a Start and Stop

for number in range(1, 6):
    print(number)

Output:

1
2
3
4
5

Using a Step

for number in range(2, 11, 2):
    print(number)

This prints even numbers from 2 through 10.

12. break Statement

The break statement immediately terminates a loop.

Example

for number in range(1, 10):
    if number == 5:
        break

    print(number)

The loop stops when number becomes 5.

Output:

1
2
3
4

13. continue Statement

The continue statement skips the remaining code in the current iteration and moves to the next iteration.

Example

for number in range(1, 6):
    if number == 3:
        continue

    print(number)

Output:

1
2
4
5

Here, the number 3 is skipped.

14. pass Statement

The pass statement does nothing. It is useful when Python requires a statement but you are not ready to write the implementation yet.

Example

age = 20

if age >= 18:
    pass
else:
    print("Under 18")

The pass statement allows the block to remain syntactically valid without performing an action.

15. Nested Loops

A loop can contain another loop. This is called a nested loop.

Example

for row in range(1, 4):
    for column in range(1, 4):
        print(row, column)

Nested loops are useful for working with tables, grids, patterns, and two-dimensional data.

16. Looping Through a Dictionary

Python dictionaries can also be processed using a for loop.

student = {
    "name": "Rahul",
    "age": 20,
    "course": "Python"
}

for key, value in student.items():
    print(key, ":", value)

The items() method provides both the dictionary key and its corresponding value.

17. for Loop with else

Python also allows an else block with a loop.

for number in range(1, 4):
    print(number)
else:
    print("Loop completed.")

The loop's else block runs when the loop finishes normally.

If the loop is terminated using break, the loop's else block does not run.

18. while Loop with else

The same concept can be used with a while loop.

count = 1

while count <= 3:
    print(count)
    count += 1
else:
    print("Counting finished.")

19. Practical Example: Simple Password Check

Let's combine conditions with user input.

password = input("Enter password: ")

if password == "python123":
    print("Login successful.")
else:
    print("Incorrect password.")

This is a small example, but the same idea can be extended into larger applications. In a real application, passwords should not be stored directly in source code.

20. Practical Example: Number Checker

number = int(input("Enter a number: "))

if number > 0:
    print("Positive number")
elif number < 0:
    print("Negative number")
else:
    print("Zero")

This program demonstrates how if, elif, and else can handle three different possibilities.

21. Practical Example: Multiplication Table

A for loop makes it easy to generate a multiplication table.

number = int(input("Enter a number: "))

for i in range(1, 11):
    print(number, "x", i, "=", number * i)

This is a good beginner exercise because it combines input, conversion, a loop, range(), and arithmetic.

Common Mistakes Beginners Make

1. Forgetting the colon

if age >= 18
    print("Adult")

The condition should end with a colon:

if age >= 18:
    print("Adult")

2. Incorrect indentation

Python relies heavily on indentation, so make sure statements inside a block are properly indented.

3. Creating an accidental infinite loop

When using while, make sure the condition can eventually become false.

4. Confusing = and ==

= assigns a value, while == compares two values.

name = "Python"

if name == "Python":
    print("Correct")

Control Flow Cheat Sheet

Statement Purpose
if Runs code when a condition is true
elif Checks another condition
else Runs when previous conditions are false
for Iterates over an iterable
while Repeats while a condition is true
break Stops a loop
continue Skips the current iteration
pass Acts as a placeholder

Practice Exercises

Before moving to the next Python topic, try solving these exercises yourself.

  1. Write a program that checks whether a number is even or odd.
  2. Write a program that finds the largest of three numbers.
  3. Print numbers from 1 to 20 using a for loop.
  4. Print only even numbers between 1 and 50.
  5. Calculate the sum of numbers from 1 to 100.
  6. Print a multiplication table for a number entered by the user.
  7. Use a while loop to count from 10 down to 1.
  8. Write a program that skips multiples of 3 using continue.
  9. Search for a number in a list and stop when it is found using break.
  10. Create a simple menu program using if-elif-else.

Frequently Asked Questions

What is control flow in Python?

Control flow determines the order in which Python executes statements. Conditions and loops are two major parts of Python control flow.

What is the difference between if and elif?

if starts a conditional check. elif allows you to check another condition when the previous condition was false.

When should I use a for loop?

Use a for loop when you want to iterate over items in a collection or another iterable, or when you need a predictable sequence of iterations.

When should I use a while loop?

A while loop is useful when repetition depends on a condition and you do not necessarily know the number of iterations in advance.

What does break do in Python?

break immediately exits the current loop.

What does continue do in Python?

continue skips the rest of the current iteration and moves to the next iteration.

What is the purpose of pass?

pass is a placeholder statement. It allows you to leave a block empty while keeping the Python code syntactically valid.

Why is indentation important in Python?

Python uses indentation to define blocks of code. Statements with the same indentation generally belong to the same block.

What is range() used for?

range() creates a sequence of numbers and is commonly used with for loops.

Can Python have a loop inside another loop?

Yes. A loop inside another loop is called a nested loop. It is commonly used when working with grids, tables, and multidimensional data.

Conclusion

Control flow is one of the most important foundations of Python programming. Once you understand conditions and loops, you can start building programs that make decisions and perform repetitive tasks automatically.

Start with simple if-else examples, then practice for and while loops. After that, experiment with break, continue, and nested loops. Writing small programs yourself is one of the best ways to make these concepts comfortable.

In the next part of this Python tutorial series, we can move to Python Strings, where you will learn indexing, slicing, useful string methods, formatting, and practical string exercises.

Previous Post Next Post