Cristhian Villegas
Backend10 min read0 views

Python Course #3: Control Structures — Conditionals and Loops

Python Course #3: Control Structures — Conditionals and Loops

Introduction: making decisions and repeating actions in your code

Welcome to Part 3 of 10 of the Python course for beginners. In the previous articles you learned how to use variables and data types. Now we are going to take a very important step: teaching your program to make decisions and repeat actions.

Python Logo

Think about your daily life: if it rains, you take an umbrella; if it does not rain, you go out without one. You repeat your alarm every morning until you get up. Your code does the same thing with control structures: conditionals (making decisions) and loops (repeating actions).

By the end of this article you will be able to write programs that react to different situations and repeat tasks automatically. Let's see it step by step.

Conditionals: if, elif, else

A conditional tells Python: "if this condition is true, do this; otherwise, do something else". The basic structure is:

python
1if condition:
2    # code that runs if the condition is true
3elif another_condition:
4    # code that runs if the second condition is true
5else:
6    # code that runs if no condition was met
📌 Important: In Python, indentation (the spaces at the beginning of a line) is mandatory. Always use 4 spaces to indicate that a block of code belongs to an if, elif, or else.

Let's look at an everyday example — deciding what clothes to wear based on the weather:

python
1temperature = 15
2
3if temperature > 30:
4    print("It's very hot, wear light clothes")
5elif temperature > 20:
6    print("The weather is nice, a t-shirt is fine")
7elif temperature > 10:
8    print("It's a bit cold, take a jacket")
9else:
10    print("It's very cold, bundle up")

In this example Python evaluates the conditions from top to bottom. As soon as it finds one that is true, it runs that block and skips the rest. If none is met, it runs the else block.

Another classic example — checking if someone can vote:

python
1age = int(input("How old are you? "))
2
3if age >= 18:
4    print("You can vote")
5else:
6    print("You cannot vote yet")

Comparison operators

For a conditional to work, you need to compare values. Python has these comparison operators:

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than10 > 7True
<Less than3 < 8True
>=Greater than or equal to5 >= 5True
<=Less than or equal to4 <= 3False
⚠️ Watch out: Do not confuse = (assign a value to a variable) with == (compare whether two values are equal). This is a very common mistake among beginners.

Let's see some quick examples:

python
1name = "Ana"
2number = 42
3
4print(name == "Ana")     # True
5print(name != "Carlos")  # True
6print(number > 50)       # False
7print(number <= 42)      # True

Logical operators: and, or, not

Sometimes you need to combine several conditions. That is what logical operators are for:

OperatorMeaningExample
andBoth conditions must be trueage > 18 and has_license
orAt least one condition must be trueis_student or is_retired
notReverses the result (true becomes false)not is_raining

Practical example — checking if someone can enter a bar:

python
1age = 20
2has_id = True
3
4if age >= 18 and has_id:
5    print("You can come in")
6elif age >= 18 and not has_id:
7    print("You are old enough but you need your ID")
8else:
9    print("You cannot come in, you are underage")

Example with or — cinema discount:

python
1age = 65
2is_student = False
3
4if age < 12 or age > 60 or is_student:
5    print("You get a discount on the ticket")
6else:
7    print("You pay the regular price")

The while loop: repeat while a condition is true

The while loop repeats a block of code as long as a condition is true. It is like saying: "while this is not done, keep doing it".

python
1counter = 1
2
3while counter <= 5:
4    print("Repetition number", counter)
5    counter = counter + 1
6
7print("Done! The loop finished")

Output:

bash
1Repetition number 1
2Repetition number 2
3Repetition number 3
4Repetition number 4
5Repetition number 5
6Done! The loop finished
⚠️ Watch out for infinite loops: If the condition never becomes false, the program will run forever. Always make sure that something inside the loop eventually makes the condition False.

Practical example — ask for a password until it is correct:

python
1correct_password = "python123"
2attempt = ""
3
4while attempt != correct_password:
5    attempt = input("Enter the password: ")
6
7print("Correct password! Welcome")

The for loop: iterating over sequences

The for loop goes through the elements of a sequence one by one. It is ideal when you know in advance how many times you want to repeat something or when you want to go through a list.

Using range()

The range() function generates a sequence of numbers. It is the most common way to use for when you want to repeat something a fixed number of times:

python
1# Print numbers from 0 to 4
2for i in range(5):
3    print(i)
4
5# Print numbers from 1 to 5
6for i in range(1, 6):
7    print(i)
8
9# Print numbers in steps of 2: 0, 2, 4, 6, 8
10for i in range(0, 10, 2):
11    print(i)
💡 Tip: range(5) generates the numbers 0, 1, 2, 3, 4 (it does not include 5). This is very common in programming and is called an "exclusive range".

Iterating over lists

You can use for to go through any list:

python
1fruits = ["apple", "banana", "orange", "grape"]
2
3for fruit in fruits:
4    print("I like", fruit)

Output:

bash
1I like apple
2I like banana
3I like orange
4I like grape

Iterating over strings

A string is a sequence of characters, so you can iterate over it too:

python
1for letter in "Python":
2    print(letter)

break and continue: controlling loop flow

Sometimes you need to exit a loop early or skip an iteration. That is what break and continue are for.

break: exit the loop immediately

python
1# Search for a number in a list
2numbers = [10, 25, 33, 47, 55, 60]
3
4for number in numbers:
5    if number == 47:
6        print("Found 47!")
7        break
8    print("Checking:", number)

Output:

bash
1Checking: 10
2Checking: 25
3Checking: 33
4Found 47!

When Python reaches break, it exits the loop immediately without checking the remaining numbers.

continue: skip to the next iteration

python
1# Print only even numbers
2for i in range(1, 11):
3    if i % 2 != 0:
4        continue  # If odd, skip to the next one
5    print(i)

Output:

bash
12
24
36
48
510

With continue, Python skips the rest of the code inside the loop for that iteration and moves directly to the next one.

Nested loops

A nested loop is a loop inside another loop. Every time the outer loop runs once, the inner loop runs completely.

Classic example — multiplication table:

python
1# Multiplication table from 1 to 5
2for i in range(1, 6):
3    print(f"--- Table of {i} ---")
4    for j in range(1, 11):
5        result = i * j
6        print(f"{i} x {j} = {result}")
7    print()  # Blank line between tables

This will print the multiplication table from 1 to 5, each one with multiplications from 1 to 10.

Another example — draw a rectangle with asterisks:

python
1rows = 4
2columns = 8
3
4for i in range(rows):
5    for j in range(columns):
6        print("*", end="")
7    print()  # New line at the end of each row

Output:

bash
1********
2********
3********
4********
💡 Tip: The end="" parameter in print() prevents a newline from being added after each asterisk. This way all the asterisks in a row are printed on the same line.

Practical example: guess the number game

Let's combine everything we learned to create an interactive game. The program will think of a random number and you will have to guess it:

python
1import random
2
3# The program "thinks" of a number between 1 and 100
4secret_number = random.randint(1, 100)
5attempts = 0
6guessed = False
7
8print("=== Game: Guess the Number ===")
9print("I have thought of a number between 1 and 100.")
10print("Try to guess it!")
11print()
12
13while not guessed:
14    # Ask the user for a number
15    answer = input("Your guess: ")
16
17    # Check that it is a valid number
18    if not answer.isdigit():
19        print("Please enter a valid number.")
20        continue
21
22    user_number = int(answer)
23    attempts = attempts + 1
24
25    # Compare with the secret number
26    if user_number < secret_number:
27        print("Too low. Try a higher number.")
28    elif user_number > secret_number:
29        print("Too high. Try a lower number.")
30    else:
31        guessed = True
32        print(f"Congratulations! You guessed the number {secret_number}")
33        print(f"You did it in {attempts} attempts.")
34
35# Final message based on performance
36if attempts <= 5:
37    print("Amazing! You are a genius.")
38elif attempts <= 10:
39    print("Very good! Nice job.")
40else:
41    print("You got it, but you can do better. Try again!")
📌 What does this program do?
  • Uses random.randint(1, 100) to generate a random number between 1 and 100
  • Uses a while loop that repeats until the user guesses correctly
  • Uses continue to handle invalid inputs
  • Uses if/elif/else conditionals to give hints to the user
  • At the end, uses conditionals to evaluate the player's performance

Summary and next article

In this article you learned the most fundamental tools for controlling the flow of your program:

  • Conditionals (if, elif, else): allow your program to make decisions
  • Comparison operators (==, !=, >, <, >=, <=): compare values to create conditions
  • Logical operators (and, or, not): combine multiple conditions
  • while loop: repeats code as long as a condition is true
  • for loop: iterates over sequences of elements (numbers, lists, strings)
  • break and continue: control when to exit a loop or skip iterations
  • Nested loops: a loop inside another loop for more complex patterns

With these tools you can now create programs that actually do interesting things. In the next article (Part 4 of 10) we will learn about functions: how to organize your code into reusable blocks so you do not repeat the same thing over and over again.

Share:
CV

Cristhian Villegas

Software Engineer specializing in Java, Spring Boot, Angular & AWS. Building scalable distributed systems with clean architecture.

Comments

Sign in to leave a comment

No comments yet. Be the first!

Related Articles