Loops
In this class, we will delve into loops, which are structures that allow a block of code to be executed repeatedly until a condition is met.
Types of loops Link to heading
while
loop: It is executed while a condition is met.for
loop: It is executed on a sequence of values.
while
loop example:
Link to heading
number = 1
while number <= 5:
print(number)
number += 1
Exit: Link to heading
1
2
3
4
5
In this example:
- The
while
loop is used to print the numbers 1 to 5. - The variable
number
is used as a counter. - The condition
number <= 5
is checked before each iteration of the loop. - If the condition is met, the code block is executed within the loop.
- If the condition is not met, the loop ends.
for
loop example:
Link to heading
name_list = ["Ana", "John", "Peter"]
for name in name_list:
print(name)
Exit: Link to heading
Ana
Juan
Pedro
In this example:
- The
for
loop is used to loop through a list of names. - The
name
variable is used to store each name in the list. - The loop is executed once for each name in the list.
break
and continue
statements:
Link to heading
- The
break
statement is used to break out of a loop before it ends. - The
continue
statement is used to move to the next iteration of the loop without executing the rest of the code.
Example: Link to heading
number = 1
while True:
if number % 2 == 0:
number += 1
continue
print(number)
number += 1
if number == 11:
break
Exit: Link to heading
1
3
5
7
9
In this example:
- The
while True
loop is used to create an infinite loop. - The statement
if number % 2 == 0
checks if the number is even. - If the number is even, the
number
variable is incremented and the next iteration of the loop continues without executing the rest of the code. - If the number is odd, the number is printed and the
number
variable is incremented. The statementif number == 11
is used to exit the loop when the variable number is equal to 11. - The
continue
statement was used to skip printing even numbers.
Exercises Link to heading
- Write a Python code that calculates the sum of the numbers from 1 to 100.
- Write a Python code that prints the even numbers from 1 to 10.