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
whileloop: It is executed while a condition is met.forloop: 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
whileloop is used to print the numbers 1 to 5. - The variable
numberis used as a counter. - The condition
number <= 5is 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
forloop is used to loop through a list of names. - The
namevariable 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
breakstatement is used to break out of a loop before it ends. - The
continuestatement 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 Trueloop is used to create an infinite loop. - The statement
if number % 2 == 0checks if the number is even. - If the number is even, the
numbervariable 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
numbervariable is incremented. The statementif number == 11is used to exit the loop when the variable number is equal to 11. - The
continuestatement 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.