Iteration in Python
Welcome to the world of loops! Today, we're going to learn about iteration, which is like teaching your computer to repeat tasks. You tell it how many times to do it and it does it over and over again - that's the power of iteration!
While Loops: The Repeating Magic
In Python, we use while loops for iteration. These loops are condition-controlled, which means they keep repeating as long as a certain condition is true.
count = 0
while count < 5:
print("Hello, World!")
count = count + 1
In this example, the loop will output "Hello, World!" five times. The loop keeps going while the count is less than 5. That is called the condition.
The Importance of Indentation
Just like with if statements, indentation is super important in while loops! It tells Python which lines of code belong to the loop.
After a while statement:
- Put a colon (:) at the end of the line
- Indent the next line (usually by pressing the Tab key ⭾ once).
x = 0
while x < 10:
print(x) # This line is part of the loop
x = x + 1 # This line is also part of the loop
print("Loop done") # This line is not indented, so it's not part of the loop
The indented lines will repeat, but the last line only runs once, after the loop is finished. This code will output 0 1 2 3 4 5 6 7 8 9 10 before outputting Loop done.
Comparison Operators: Making Decisions
To control our loops, we use comparison operators. Here are some important ones:
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
answer = ""
while answer != "quit":
answer = input("Enter 'quit' to exit: ")
This loop will keep asking for input until the user types "quit". That could be once or it could be stuck in an infinite loop, going on forever.
Putting It All Together
Let's use everything we've learned to make a program that adds up numbers:
total = 0
number = int(input("Enter a number (0 to stop)"))
while number != 0:
total = total + number
number = int(input("Enter a number (0
to stop)"))
print("The sum is", total)
print("The sum is " + str(total))
This program:
- Asks the user to input a number
- While the number entered isn't a 0
- Adds all the numbers up and asks again
- When the user enters a 0, it stops asking and outputs the total
Now it's your turn! Can you make a program that keeps asks a word until they type it in? Press inspire me! for more ideas of what to code.
Write a program to...