Lesson 9 of 16 in Python for Biologists, a free beginner course with ecology examples.
Fieldwork is full of “keep going until” jobs. Keep setting traps until you have 30 captures. Keep checking the nest box until it is occupied. Keep charging the camera trap battery until it is full. You do not know in advance how many rounds it will take, only when to stop. That is exactly what a while loop is for.
Quick answer: A Python while loop repeats a block of code as long as a condition is True. Python checks the condition, runs the indented block, then checks again, and stops as soon as the condition is False. Every while loop needs three things: a starting value, a condition, and a line inside the loop that changes the value, otherwise the loop never ends.

What You Will Learn in This Lesson
- How a
whileloop works and the three parts it needs - How to count up, count down and step by more than 1
- What an infinite loop is and how to stop one
- How to repeat questions with
input()until the answer is valid - How to write a “do while” loop in Python with
while True - How to combine conditions with
andandorwithout getting them backwards - How nested while loops work
What Is a while Loop in Python?
A while loop looks like an if statement from lesson 7, with one difference: an if runs its block once, a while runs it again and again for as long as the condition stays true.
while condition:
code that repeats while the condition is TrueThe same rules apply as for if: the line ends with a colon, and the repeated block is indented by 4 spaces. Here is a camera trap battery charging from 50% in steps of 10%:
battery = 50 # 1. starting value
while battery < 100: # 2. condition
print(f"Battery at {battery}%. Charging...")
battery += 10 # 3. update
print("Battery full. Unplug the charger.")Battery at 50%. Charging...
Battery at 60%. Charging...
Battery at 70%. Charging...
Battery at 80%. Charging...
Battery at 90%. Charging...
Battery full. Unplug the charger.Each pass through the loop is called an iteration. When battery reaches 100, the condition battery < 100 becomes False, Python skips the block and continues with the first line after the loop.
What Are the Three Parts of a while Loop?
- A starting value before the loop:
battery = 50. - A condition that is checked before every round:
battery < 100. - An update inside the loop that moves the value towards the end:
battery += 10.
Forget the first and you get a NameError. Forget the third and the loop runs forever.
How Do I Count With a while Loop?
The update line decides the direction and the size of each step.
Counting down, for example nights left in a survey:
nights = 3
while nights > 0:
print(f"{nights} nights left")
nights -= 1
print("Survey complete.")3 nights left
2 nights left
1 nights left
Survey complete.Spotted the “1 nights”? The ternary operator from lesson 8 fixes it: word = "night" if nights == 1 else "nights". You will do exactly that in Task 5.
Counting in steps of 2, for example every second plot along a transect:
plot = 0
while plot <= 10:
print(plot)
plot += 2This prints 0, 2, 4, 6, 8 and 10, each on its own line.
What Is an Infinite Loop in Python?
An infinite loop is a loop whose condition never becomes False. The most common cause is a missing or misplaced update line:
battery = 50
while battery < 100:
print(f"Battery at {battery}%. Charging...")
battery += 10 # not indented, so it is outside the loopBecause battery += 10 is not indented, it is not part of the loop. battery stays at 50 forever, and the same line is printed thousands of times per second.
How Do I Stop an Infinite Loop?
Press Ctrl + C in the terminal. Python stops the program and shows KeyboardInterrupt. In VS Code you can also click the stop square in the terminal panel. No harm done: find the bug and run it again.
Before you run a new while loop, ask yourself one question: which line inside the loop makes the condition false eventually? If you cannot point to it, you have an infinite loop.
How Do I Use a while Loop With input()?
In lesson 6 we said that users sometimes type nonsense, and that a loop can ask again. Here it is. The loop keeps asking until the count makes sense:
eggs = int(input("Number of eggs: "))
while eggs < 0:
print("A count cannot be negative.")
eggs = int(input("Number of eggs: "))
print(f"Recorded: {eggs} eggs")Number of eggs: -3
A count cannot be negative.
Number of eggs: 4
Recorded: 4 eggsIf the first answer is already fine, the condition is false straight away and the loop body never runs. A while loop can run zero times.
Reading Values Until the User Types 0
A classic exercise: print every count the user types from a data sheet, and stop when they type 0. Watch the order of the lines, because it is easy to get wrong:
count = int(input("Enter a count (0 to stop): "))
while count != 0:
print(count)
count = int(input("Enter a count (0 to stop): "))Read first, then loop: check, print, read the next one. If you read inside the loop before printing, you skip the first count and print the 0 at the end, which is the bug in many first attempts.
Does Python Have a do while Loop?
No. Some languages have a do while loop, which always runs at least once and checks the condition at the end. Python does it with while True and break:
checks = 0
while True:
checks += 1
answer = input("Is the nest box occupied? (yes/no) ")
if answer == "yes":
break
print("Empty. Check again tomorrow.")
print(f"Occupied after {checks} checks. Start recording.")Is the nest box occupied? (yes/no) no
Empty. Check again tomorrow.
Is the nest box occupied? (yes/no) yes
Occupied after 2 checks. Start recording.while True on its own would run forever. break jumps out of the loop immediately, so the loop ends exactly when the answer is “yes”. You will learn more about break and its partner continue in lesson 12.
How Do I Use and and or in a while Loop?
Often a loop should stop for more than one reason. A trapping session ends when you have 100 captures or when you run out of nights, whichever comes first.
Here is the trick that saves a lot of confusion: the while condition describes when to keep going, not when to stop. You keep trapping while you still need captures and you still have nights:
max_captures = 100
nights_left = 7
captures = 0
while captures < max_captures and nights_left > 0:
captures += 18 # simulate one night of trapping
nights_left -= 1
print(f"Captures: {captures}, nights left: {nights_left}")
print("Trapping session over.")Captures: 18, nights left: 6
Captures: 36, nights left: 5
Captures: 54, nights left: 4
Captures: 72, nights left: 3
Captures: 90, nights left: 2
Captures: 108, nights left: 1
Trapping session over.The loop stopped after night 6, because the captures goal was reached, even though one night was left.
Why Does or Make the Loop Run Longer?
A very common mistake is to translate “stop when A or B happens” into while A or B. Watch what happens with or:
max_captures = 100
nights_left = 7
captures = 0
while captures < max_captures or nights_left > 0:
captures += 18
nights_left -= 1
print(f"Captures: {captures}, nights left: {nights_left}")Captures: 126, nights left: 0With or, the loop keeps going as long as either part is true, so it only stops when both are false: the goal is reached and the nights are used up. One extra night of trapping you did not need.
The rule to remember:
- Stop when any of several things happens → keep going with
and. - Stop only when all of them have happened → keep going with
or.

Can I Put an if Inside a while Loop?
Yes, and you will do it all the time. The if runs on every round and reacts to the current values without stopping the loop:
nights_left = 3
while nights_left > 0:
if nights_left == 1:
print("Last night: collect all traps in the morning.")
else:
print(f"Trapping night. {nights_left} nights left.")
nights_left -= 1Trapping night. 3 nights left.
Trapping night. 2 nights left.
Last night: collect all traps in the morning.
What Is a Nested while Loop?
A loop inside a loop. For every round of the outer loop, the inner loop runs completely. This prints a small triangle, one more star per row:
row = 1
while row <= 4:
star = 0
while star < row:
print("*", end="")
star += 1
print()
row += 1*
**
***
****end="" tells print() not to start a new line, so the stars of one row stay together. The empty print() after the inner loop ends the row. Notice that star = 0 sits inside the outer loop, so the inner count restarts on every row.
The official docs describe the while statement in one short paragraph. For more worked examples, Real Python has a long guide to while loops.
Practice Tasks
Task 1: Transect Markers
You place a marker every 2 metres along a 100 metre transect, starting at 0. Print every marker position with a while loop.
Show the solution
position_m = 0
while position_m <= 100:
print(position_m)
position_m += 2Starting at 0 and stepping by 2 only ever visits even numbers, so no if is needed. In the next lesson you will write the same thing with a for loop.
Task 2: Point Count Countdown
A bird point count lasts 10 minutes. Print the minutes left, from 10 down to 1, with a while loop.
Show the solution
minutes_left = 10
while minutes_left > 0:
print(minutes_left)
minutes_left -= 1Task 3: Enter Counts Until 0
You are typing in counts from a paper data sheet. Read the counts one by one and print each one, until you type 0 to mark the end of the sheet. Do not print the 0. Write it twice: once with the condition in the while line, once with while True and break.
Show the solution
# Version 1: condition in the while line
count = int(input("Enter a count (0 to finish): "))
while count != 0:
print(count)
count = int(input("Enter a count (0 to finish): "))# Version 2: while True with break
while True:
count = int(input("Enter a count (0 to finish): "))
if count == 0:
break
print(count)The second version needs the input() line only once, which is why many programmers prefer it.
Task 4: Seedling Bar Chart
One new seedling emerges in your plot every day for 5 days. Use two nested while loops to print one row of stars per day, showing the total number of seedlings so far:
*
**
***
****
*****Show the solution
day = 1
while day <= 5:
star = 0
while star < day:
print("*", end="")
star += 1
print()
day += 1A shortcut you will like: strings can be multiplied, so print("*" * day) replaces the whole inner loop. That is a quick text bar chart for any count.
Task 5: Field Season Countdown
Start at 7 days and count down. Print 7 days until the field season! and so on, with the correct “day” or “days”, and finish with The field season starts today!
Show the solution
days = 7
while days > 0:
word = "day" if days == 1 else "days"
print(f"{days} {word} until the field season!")
days -= 1
print("The field season starts today!")Task 6: Keep Calling
You need a data file from a colleague who is not picking up. Ask Did they answer? (yes/no) again and again until the answer is yes, then print how many calls it took.
Show the solution
calls = 1
answer = input("Did they answer? (yes/no) ")
while answer != "yes":
calls += 1
answer = input("Did they answer? (yes/no) ")
print(f"Connected after {calls} calls.")What if they never answer? In real code you would add a limit, for example while answer != "yes" and calls < 10, so the loop cannot run forever.
Task 7: Bait Stock and Deadline
You start the day with 50 bait portions and an 8 hour shift. Every hour you use 7 portions. Keep working while there are at least 10 portions and time left. Print the stock every hour, warn when it drops below 15, and print why the work stopped.
Show the solution
bait = 50
hours_left = 8
while bait >= 10 and hours_left > 0:
bait -= 7
hours_left -= 1
print(f"Bait left: {bait}, hours left: {hours_left}")
if bait < 15:
print("Warning: bait is running low!")
if bait < 10:
print("Stopped: bait below the critical level.")
else:
print("Stopped: the shift is over.")Bait left: 43, hours left: 7
Bait left: 36, hours left: 6
Bait left: 29, hours left: 5
Bait left: 22, hours left: 4
Bait left: 15, hours left: 3
Bait left: 8, hours left: 2
Warning: bait is running low!
Stopped: bait below the critical level.“Stop when bait is low or time is up” becomes “keep going while bait is fine and time is left”. The if after the loop tells you which condition ended it.
Task 8: Predict the Rounds
How many times does each loop print? Work it out first, then run it.
# Loop A: a cell culture that doubles each hour
cells = 1
while cells < 20:
print(cells)
cells *= 2
# Loop B: the nest target is 5, and you already have 10
nests = 10
while nests < 5:
print(nests)
nests += 1Show the solution
Loop A prints 5 times: 1, 2, 4, 8 and 16. The next value, 32, fails the condition. Loop B prints nothing at all: 10 is not less than 5, so the condition is false from the start and the body never runs.
Quiz: Python while Loop
1. When does a while loop stop?
a) after 10 rounds b) when its condition is False c) when it reaches the last line of the program
Show answer
b) Python checks the condition before every round.
2. What usually causes an infinite loop?
a) a missing colon b) no line inside the loop that changes the condition c) using input()
Show answer
b) A missing colon gives a SyntaxError instead.
3. How do you stop a program stuck in an infinite loop?
a) Ctrl + C b) Ctrl + Z c) type stop
Show answer
a) Ctrl + C
4. Can a while loop run zero times?
a) yes b) no
Show answer
a) yes, if the condition is False from the start.
5. Does Python have a do while loop?
a) yes, called do b) no, you use while True with break
Show answer
b)
6. You want to stop when captures reach 100 OR nights run out. Which condition keeps the loop going?
a) captures < 100 or nights > 0 b) captures < 100 and nights > 0
Show answer
b) Keep going only while both are still fine. Version a) keeps going until both have run out.
7. What does this print?
n = 3
while n > 0:
n -= 1
print(n)a) 3 b) 1 c) 0
Show answer
c) 0. The print is outside the loop, so it runs once, after the loop has finished.
8. What does print("*", end="") do?
a) prints a star and starts a new line b) prints a star and stays on the same line c) prints nothing
Show answer
b)
Key Takeaways
- A
whileloop repeats its block as long as the condition isTrue. - Every loop needs a starting value, a condition and an update inside the loop.
- No update, or an update outside the loop, means an infinite loop. Ctrl + C stops it.
- A while loop is perfect for repeating
input()until the answer is valid. - Python has no do while loop. Use
while Truewithbreak. - Write the condition for keeping going. To stop at the first of several limits, join them with
and.
Previous lesson: Python Ternary Operator
Next lesson: Python for Loop and range().
Back to the course: Python for Biologists, all 16 lessons

Erzsebet Frey (Eli Frey) is an ecologist and online entrepreneur with a Master of Science in Ecology from the University of Belgrade. Originally from Serbia, she has lived in Sri Lanka since 2017. Eli has worked internationally in countries like Oman, Brazil, Germany, and Sri Lanka. In 2018, she expanded into SEO and blogging, completing courses from UC Davis and Edinburgh. Eli has founded multiple websites focused on biology, ecology, environmental science, sustainable and simple living, and outdoor activities. She enjoys creating nature and simple living videos on YouTube and participates in speleology, diving, and hiking. ORCID: 0009-0002-7482-7986
From the shop
Gifts for people who love the wild
Wildlife themed t-shirts, notebooks, tote bags, bandanas and guides, designed by an ecologist.
Visit the shop
