"Loops are engines of automation in the world of code."
Let's take a look on while
loop. It runs until the condition for the loop is True
.
while condition:
# Code to execute while the condition is True
Scenario #1: Validation of the user input.
# The loop keeps asking for input until the user enters a positive number.
number = 0
while number <= 0:
number = int(input("Enter a number > 0: ")) # Note: that indent is required to use ``while``
# Exit the loop in case we entered the ``number > 0``
print(f"Your number is > 0 and it is {number}")
Enter a number > 0: -2
Enter a number > 0: 0
Enter a number > 0: 11
Your number is > 0 and it is 11
Scenario #2: Repeat until specific input
response = ''
while response.lower() != 'exit':
response = input("Type 'exit' to stop: ")
print("Exited successfully!")
Type 'exit' to stop: what?
Type 'exit' to stop: I don't understand
Type 'exit' to stop: exit
Exited successfully!
Loops
are extremely powerfull tools in programming languages and the examples provided are not single possible. Be creative! And come up with solutions,which will satisfy your needs!
while
loops are best used when the number of iterations is not known in advance.for
loops are ideal when iterating over a sequence or range.
The table provided below helps to make a decision based on the appropriatness of usage for
and while
Aspect | while |
for |
---|---|---|
Control | Based on a boolean condition. | Based on iterating over a sequence. |
Usage | Unknown number of iterations. | Known number of iterations. |
Flexibility | More flexible, can lead to infinite loops. | Less prone to errors, more structured. |
Sometimes we can achieve the identical result using either while
or for
loops, but with different syntax.
counter = 0 # Define a counter
while counter < 5:
print(counter)
counter += 1 # Each iteration add ``1`` to its value
# Add empty line between outputs
print()
# The ``for`` loop serves the same purpose as `while`
for counter in range(5):
print(counter)
0
1
2
3
4
0
1
2
3
4
Infinite loops occur when the loop condition is always True
. They should be used extremely cautiously. As this can block the program from I/O
(input/output
) operations.
Make sure that you always exit
the infinite loop
based on some conditions, using the break
keyword described in section 2
.
while True:
print("This loop will run forever...")
# The program prints "This loop will run forever..." indefinitely
Loops in Python can be controlled using break
, continue
, and else
statements. These control statements help in managing loop execution more precisely based on certain conditions.
Keyword | Description |
---|---|
break |
Exits the loop immediately, skipping the remaining iterations. |
continue |
Skips the current iteration and continues with the next one. |
else |
Executes a block of code after the loop completes normally. |
The break
statement is used to exit a loop prematurely when a certain condition is met.
- To stop the loop when a specific condition occurs.
- In search operations when the item is found.
- To avoid unnecessary processing once the goal is achieved.
Objective: We want to exit the loop once number equals to 5.
for number in range(10):
if number == 5:
break
print(number)
It is important to understand, that we can use these keywords, in any type of loop we want. And put the condition which suits the technical task.
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
0
1
2
3
4
The continue
is used to skip the rest of the loop block and move to the next iteration.
- To skip specific iterations that do not meet certain criteria.
- To avoid executing certain parts of the loop for specific conditions.
Objective: We want to output only odd numbers within range(0,10)
.
for number in range(10):
if number % 2 == 0:
continue # Skip the iteration once we meet the criteria in ``if`` statement
print(number)
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue # Skip the iteration once we meet the criteria in ``if`` statement
print(count)
1
3
5
7
9
The else
clause is executed after the loop completes its execution without hitting a break
statement.
- To check if a loop has completed normally without any
break
. - To perform certain final actions after loop completion.
Objective: We want to assure that loop has completed without exiting.
# Example of else with a for loop
for number in range(3):
print(number)
if number >= 2:
print('123213')
break
else:
print("No Break")
0
1
2
No Break
With control statements, you can create loops that handle a wide range of dynamic conditions and scenarios. Try it yourself!
Objective: Write a program that simulates a menu navigation system using a while loop and break statement.
The user can select from a list of options, and the loop terminates when the user selects the 'Exit'
option.
Input:
1. Start Game
2. Load Game
3. Exit
Choose an option: 3
Output:
Exiting the menu...
Objective: Create a program that prints out all numbers from 1 to 20, but skips odd numbers using one of control statements.
Output:
2
4
6
8
10
12
14
16
18
20
Objective: Develop a script that identifies whether a number is prime. Use a for
else
construction. If the loop completes without breaking, the number is prime.
Input: Enter a number: 11
Output: 11 is a prime number.
Objective: Simulate an escape room challenge where the user must find the correct code to "escape the room." The loop should break once the correct code is entered.
Input:
Enter the escape code: 1234
Wrong code, try again.
Enter the escape code: 9999
Correct! You've escaped!
Output:
You've successfully escaped the room!
Objective: Write a program that asks users to enter their age and ensures the input is valid using a while loop. If the input is not a number, use continue to prompt them again until a valid number is entered.
Input:
Enter your age: twenty
Invalid input, please enter a number.
Enter your age: 20
Output:
Age entered: 20
Nested loops in Python
are when you have a loop running inside another loop.
Sounds scary, right? I remember myself, when I started learning programming, the concept of nested loops was one of the harderst to undersatand.
I wanted to quit programming studying this section. But now, I will try to explain everything to you to make nested loops clear! Don't be afraid of nested loops!
The great example can be a clock
where:
- The hour hand completes one full rotation while the minute hand completes 12 full.
- The minute hand completes one full rotation (outer loop), while the second hand completes 60 full rotations (inner loop).
NOTE: The inner loop
completes its execution for every iteration of the outer loop
.
# Outer loop for the hour hand
for hour in range(12):
# Inner loop for the minute hand
for minute in range(60):
# Another inner loop for the second hand
for second in range(60):
print(f"{hour} hours {minute} minutes {second} seconds")
# Firstly the ``second's`` loop is going to be executed
0 hours 0 minutes 0 seconds
0 hours 0 minutes 1 seconds
0 hours 0 minutes 2 seconds
0 hours 0 minutes 3 seconds
0 hours 0 minutes 4 seconds
# Secondly, ``minutes'`` inner loop and lastly, the ``hours``
Imagine fans in a stadium chanting. For each round (outer loop)
they clap several times (inner loop)
.
# Outer loop for each chanting round
for round in range(3):
print("Let's go, team!")
# Inner loop for clapping
for clap in range(3):
print("Clap!", end=' ')
print() # New line after the claps
Let's go, team!
Clap! Clap! Clap!
Let's go, team!
Clap! Clap! Clap!
Let's go, team!
Clap! Clap! Clap!
Let's create a multiplication table for numbers 1 to 3, up to the times 10.
The outer loop
can iterate over the numbers you want to multiply
, and the inner loop
can iterate over the range of multipliers
.
# For numbers 1, 2, 3
for i in range(1, 4):
# From 1 times to 10 times
for j in range(1, 11):
print(f"{i} x {j} = {i*j}")
print() # New line
# 1st work of the outer loop
1 x 1 = 1
1 x 2 = 2
...
1 x 10 = 10
# 2nd work of the outer loop
2 x 1 = 2
2 x 2 = 4
...
2 x 10 = 20
# 3rd work of the outer loop
3 x 1 = 3
3 x 2 = 6
...
3 x 9 = 27
You can use Python Visualizer
in order to understand the concept of nested loops
better.
There are lots of practical cases where software engenieer can use nested loops. You will notice, that we sometimes coming back to them working with advanced data structures.
Objective: Write a program that simulates a digital clock counting down hours, minutes, and seconds from a given time.
Input:
Enter the countdown start time (hh mm ss): 01 30 00
Output:
1 hours 29 minutes 59 seconds
1 hours 29 minutes 58 seconds
...
0 hours 0 minutes 1 seconds
Time's up!
Objective: Create a program that prints out a pattern of stars, forming a right-angled triangle.
Input:
Enter the number of rows for the triangle: 5
Output:
*
**
***
****
*****
Objective: Develop a script that prints out a matrix of numbers, where each row contains numbers incremented by 1 from the previous row.
Input:
Enter the number of rows: 3
Enter the number of columns: 4
Output:
1 2 3 4
2 3 4 5
3 4 5 6
What is the output of the following code snippet?
i = 3
while i > 0:
i -= 1
if i == 2:
break
else:
print("Loop ended without break.")
Which of the following is an infinite loop?
A)
i = 5
while i > 0:
print(i)
i -= 1
B)
while True:
print("Python")
C)
for i in range(5, 0, -1):
print(i)
What will be printed by the following code?
for i in range(3):
for j in range(2):
print(j, end='')
print(i)
What does the continue keyword do in a loop?
A) Exits the loop
B) Skips to the next iteration of the loop
C) Does nothing
D) Restarts the loop
When will the 'else' part of a 'loop' execute?
A) When the loop finishes normally without encountering a break statement
B) When the loop encounters a break statement
C) At the end of each loop iteration
D) The else part is not valid for loops
Objective:: Write a program that selects a random number and asks the user to guess it. Use a while loop to allow multiple attempts until they guess correctly or choose to exit.
Input:
Guess the number: 8
Wrong! Try again or type 'exit' to stop: 5
Wrong! Try again or type 'exit' to stop: exit
Output:
The correct number was 7. Better luck next time!
Objective:: Write a program using nested loops to match the following output.
Output:
1
22
333
4444
55555
Objective:: Create a program that computes the factorial of a given number using a for
loop.
Input:
Enter a number to calculate the factorial: 5
Output:
The factorial of 5 is 120.