⬅️ Condition-controlled iteration practice with while
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. Imagine if you could tell your computer to do your chores 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 print "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.
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".
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)
This program asks the user to enter numbers and adds them up. It keeps going until the user enters 0, then it prints the total sum.
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...

