Python Basics series — Part 5. This post continues Part 1: What Every Beginner Should Know, Part 2: Variables and Data Types, Part 3: Lists and Dictionaries, and Part 4: If Statement. Each post in the series takes one topic and covers it in depth. This one covers user input and while loops.
Up to now, every program in this series has worked with data written directly into the code. That’s fine for learning, but real programs need to interact: ask a question, wait for an answer, and respond. A quote calculator needs to know how many pages you want. A quiz needs your answers. A command-line tool needs to know what you want it to do next.
That’s where two tools come in. The input() function lets your program ask the user for information. The while loop lets your program keep doing something for as long as a condition is true — like asking again until it gets a valid answer, or running until the user types quit.
In this post, you’ll learn how to get input, convert and check it, and write while loops that repeat exactly as long as they should — without accidentally running forever.
Run these examples as a script. Because they wait for you to type, these examples are easiest to try in a file. Save the code as something like
practice.pyand run it withpython3 practice.pyin your terminal.
Getting Input with input()
The input() function shows a message, called a prompt, waits for the user to type something and press Enter, and then gives you what they typed:
name = input("What's your name? ")
print(f"Nice to meet you, {name}!")
When you run it, the program pauses at the prompt:
What's your name? Maria
Nice to meet you, Maria!
Notice the space at the end of "What's your name? ". Without it, the user’s answer would appear right up against the question mark.
For longer prompts, you can build the message in a variable first:
prompt = "Tell us about your business so we can recommend a package."
prompt += "\nWhat kind of business do you run? "
business = input(prompt)
The \n adds a line break, so the question appears on its own line under the explanation.
Cleaning Up What People Type
People add extra spaces and use capital letters inconsistently. Clean the answer before you use it — .strip() removes spaces at both ends, and .lower() makes it lowercase so comparisons work:
answer = input("Do you need hosting? (yes/no) ").strip().lower()
if answer == "yes":
print("We'll include hosting in your quote.")
Now "Yes", " YES ", and "yes" all count as yes.
Input Is Always Text
This is the most important thing to remember about input(): it always returns a string, even if the user types a number. As you learned in Part 2, you can’t do math with text:
pages = input("How many pages do you need? ") # the user types 5
print(pages * 2) # 55 — the text "5" repeated twice, not 10!
Convert the input with int() or float() before you use it as a number:
pages = int(input("How many pages do you need? "))
print(pages * 2) # 10
Checking Before You Convert
If the user types something that isn’t a number, int() raises a ValueError and the program crashes:
How many pages do you need? five
ValueError: invalid literal for int() with base 10: 'five'
For whole numbers, you can check first with the string method .isdigit(), which returns True only if every character is a digit:
pages = input("How many pages do you need? ").strip()
if pages.isdigit():
pages = int(pages)
print(f"A {pages}-page website. Great!")
else:
print("Please enter a whole number, like 5.")
.isdigit() doesn’t accept decimals or negative numbers. For those, there’s a more general tool, try and except, which you’ll see later in this post. But first, we need a way to ask again when the answer is wrong. That’s what while loops are for.
While Loops
A while loop repeats a block of code as long as its condition is true. It looks a lot like an if statement — a keyword, a condition, a colon, and an indented block:
count = 1
while count <= 5:
print(count)
count += 1
This prints the numbers 1 through 5. Here’s what happens step by step:
- Python checks the condition
count <= 5. It’sTrue(1 is less than or equal to 5), so it runs the block: prints1, then adds 1 tocount. - Python goes back to the top and checks the condition again.
countis now 2, stillTrue, so it runs the block again. - This repeats until
countbecomes 6. Now the condition isFalse, so Python skips the block and continues with whatever comes after the loop.
The difference from if: an if statement runs its block once at most. A while loop keeps going back and checking again.
While vs. For
Part 1 also introduced for loops. Both repeat code, but they’re suited to different jobs:
- Use a
forloop when you know what you’re looping over: every item in a list, every key in a dictionary, or a fixed number of times withrange(). - Use a
whileloop when you don’t know in advance how many times you’ll need to repeat — you just know the condition for stopping. “Keep asking until the answer is valid.” “Keep running until the user quits.” “Keep going until the list is empty.”
Avoiding Infinite Loops
If a while loop’s condition never becomes False, the loop runs forever. This is called an infinite loop, and every programmer writes one sooner or later. The most common cause is forgetting to update the variable in the condition:
count = 1
while count <= 5:
print(count)
# forgot count += 1, so count is always 1 and this never stops
If your program gets stuck in an infinite loop, press Ctrl + C in the terminal to stop it. Then check that something inside the loop eventually makes the condition False.
Letting the User Decide When to Stop
Here’s a loop that repeats a message back until the user types quit. The value "quit" is called a sentinel: a special value that signals the end:
message = ""
while message != "quit":
message = input("Type something (or 'quit' to stop): ").strip().lower()
if message != "quit":
print(f"You said: {message}")
Notice that message starts as an empty string, so the condition is True the first time and the loop can begin. Also notice the if inside the loop: without it, the program would repeat quit back to the user before stopping.
Using a Flag
When a loop could end for several different reasons, it’s often clearer to use a single flag variable that tracks whether the program should keep running:
active = True
while active:
command = input("Enter a command (help, status, quit): ").strip().lower()
if command == "quit":
active = False
elif command == "help":
print("Available commands: help, status, quit")
elif command == "status":
print("All systems running.")
else:
print(f"Unknown command: {command}")
Any part of the loop can set active = False to end it. The while line stays short and readable.
Break and Continue
Two keywords give you more control inside a loop.
Exiting a Loop with break
break exits the loop immediately, skipping any code left in the block and ignoring the condition. A very common pattern is while True — a loop that would run forever — with a break that ends it when you’re done:
while True:
city = input("Enter a city you'd like to visit (or 'quit'): ").strip()
if city.lower() == "quit":
break
print(f"I'd love to go to {city.title()}!")
print("Thanks for playing.")
while True reads naturally: “keep doing this until something tells you to stop.” It also avoids the need to set up a starting value just so the condition passes the first time.
Skipping Ahead with continue
continue skips the rest of the current pass through the loop and jumps straight back to the condition. This loop prints only the odd numbers from 1 to 10:
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue # even number: skip the print below
print(number)
Notice that number += 1 comes before the continue. If it came after, an even number would skip the update and the loop would get stuck on it forever.
Asking Until the Answer Is Valid
Now you can solve the problem from earlier: when the user types something invalid, ask again instead of crashing.
while True:
pages = input("How many pages do you need? ").strip()
if pages.isdigit() and int(pages) > 0:
pages = int(pages)
break
print("Please enter a whole number greater than 0.")
print(f"Got it: {pages} pages.")
A session might look like this:
How many pages do you need? five
Please enter a whole number greater than 0.
How many pages do you need? 0
Please enter a whole number greater than 0.
How many pages do you need? 6
Got it: 6 pages.
Handling Any Number with try and except
.isdigit() only works for whole, positive numbers. To accept prices like 19.99 or negative numbers, use try and except. Python tries the code in the try block; if a ValueError happens, it runs the except block instead of crashing:
while True:
answer = input("What's your monthly budget? $").strip()
try:
budget = float(answer)
break
except ValueError:
print("Please enter a number, like 1500 or 1499.99.")
print(f"Budget: ${budget:,.2f}")
If float(answer) works, the break runs and the loop ends. If it fails, Python jumps to except, prints the message, and the loop asks again. You’ll learn much more about handling errors in Part 8: Files and Exceptions; for now, this pattern is all you need to read numbers safely.
While Loops with Lists and Dictionaries
while loops pair naturally with the lists and dictionaries from Part 3.
Moving Items Between Lists
A while loop can keep working until a list is empty. Remember that an empty list counts as false, so while unreviewed: means “while there are still items left”:
unreviewed = ["Home", "About", "Services", "Contact"]
approved = []
while unreviewed:
page = unreviewed.pop(0) # take the first page off the list
print(f"Reviewing {page}...")
approved.append(page)
print(f"Approved pages: {approved}")
print(f"Left to review: {unreviewed}")
Reviewing Home...
Reviewing About...
Reviewing Services...
Reviewing Contact...
Approved pages: ['Home', 'About', 'Services', 'Contact']
Left to review: []
Removing Every Copy of a Value
In Part 3, you saw that removing items from a list while looping over it with for skips items. .remove() only deletes the first match — but a while loop can keep calling it until no copies are left:
tags = ["old", "web", "old", "seo", "old"]
while "old" in tags:
tags.remove("old")
print(tags) # ['web', 'seo']
Filling a Dictionary from User Input
This loop collects answers from several people into a dictionary until there’s no one left to ask:
responses = {}
while True:
name = input("What's your name? ").strip()
color = input("What's your favorite brand color? ").strip()
responses[name] = color
again = input("Is there someone else? (yes/no) ").strip().lower()
if again != "yes":
break
print("--- Results ---")
for name, color in responses.items():
print(f"{name} likes {color}.")
Putting It All Together: A Project Intake Tool
Here’s a small command-line program that collects the details for a new website project. It uses everything from this post — plus the lists, dictionaries, and if statements from earlier parts:
HOURLY_RATE = 85
HOURS_PER_PAGE = 4
print("Welcome! Let's plan your new website.")
# Required text: ask until it isn't empty
while True:
business = input("Business name: ").strip()
if business:
break
print("The business name can't be empty.")
# A list of pages, collected until the user types 'done'
pages = []
print("Enter the pages you need, one at a time. Type 'done' when finished.")
while True:
page = input("Page name: ").strip().title()
if page.lower() == "done":
if pages:
break
print("Please add at least one page.")
continue
if page in pages:
print(f"{page} is already on the list.")
continue
if page:
pages.append(page)
# A yes/no question that only accepts yes or no
while True:
rush = input("Do you need it within 2 weeks? (yes/no) ").strip().lower()
if rush in ("yes", "no"):
break
print("Please answer yes or no.")
# Calculate and show the quote
hours = len(pages) * HOURS_PER_PAGE
total = hours * HOURLY_RATE
if rush == "yes":
total = total * 1.25
print(f"\nQuote for {business}")
for number, page in enumerate(pages, start=1):
print(f" {number}. {page}")
print(f"Estimated hours: {hours}")
print(f"Rush delivery: {'Yes' if rush == 'yes' else 'No'}")
print(f"Total: ${total:,.2f}")
Here’s a sample session, including a few mistakes to show the validation working:
Welcome! Let's plan your new website.
Business name:
The business name can't be empty.
Business name: Bright Bakery
Enter the pages you need, one at a time. Type 'done' when finished.
Page name: done
Please add at least one page.
Page name: home
Page name: menu
Page name: Home
Home is already on the list.
Page name: contact
Page name: done
Do you need it within 2 weeks? (yes/no) maybe
Please answer yes or no.
Do you need it within 2 weeks? (yes/no) no
Quote for Bright Bakery
1. Home
2. Menu
3. Contact
Estimated hours: 12
Rush delivery: No
Total: $1,020.00
Run it yourself and try to break it: leave fields blank, type the same page twice, or answer “maybe”. Then try extending it — ask for a budget with try/except, or warn the user if their budget is lower than the quote.
Common Beginner Mistakes
Forgetting to update the loop variable. If nothing inside the loop changes the condition, the loop never ends. Make sure every path through the loop moves toward stopping, and remember Ctrl + C to stop a runaway program.
Comparing input to a number. input() returns text, so if answer == 5: is never true — "5" and 5 aren’t equal. Convert with int() first, or compare to the string "5".
Not cleaning the input. if answer == "yes": fails when the user types "Yes" or " yes". Use .strip().lower() on answers you compare.
Putting continue before the update. If continue runs before the line that changes the loop variable, the loop gets stuck. Update the variable first.
Using while where for is simpler. To go through every item in a list or repeat something a fixed number of times, a for loop is shorter and can’t accidentally run forever:
# Works, but more code and easy to get wrong
i = 0
while i < len(pages):
print(pages[i])
i += 1
# Simpler
for page in pages:
print(page)
Using break outside a loop. break and continue only work inside a loop. Using them anywhere else is a SyntaxError.
Converting without checking. int(input(...)) crashes on anything that isn’t a whole number. When the input comes from a person, validate it in a loop with .isdigit() or try/except.
Practice Exercises
- Ask for the user’s name and favorite programming language, then print a sentence using both.
- Write a countdown that asks for a starting number and counts down to 1 with a
whileloop, then printsLiftoff!. - Keep asking the user for numbers until they type
done, then print how many numbers they entered, the total, and the average. - Write a number-guessing game: pick a secret number, keep asking for guesses, say “too high” or “too low” after each one, and congratulate the user when they get it right. Count how many guesses it took.
- Ask for a password until it’s at least 8 characters long and contains at least one digit. (Hint:
any(c.isdigit() for c in password).) - Build a simple to-do list program that accepts the commands
add,list,remove, andquit.
Exercise 4 is a classic. You can compare your version with the one in 100 Days of Python: Day 005 Number Guessing Game.
Conclusion
input() and while loops turn your scripts into programs people can actually talk to. input() collects information — always as text, so remember to clean it with .strip() and .lower() and convert it with int() or float(). while loops repeat code for as long as a condition is true, which makes them perfect for asking until the answer is valid, running until the user quits, or working through a list until it’s empty.
Use break to leave a loop as soon as you’re done, continue to skip ahead, and a flag when a loop can end in several ways. Above all, make sure every loop has a way out.
Next in the Python Basics series: Functions, how to package your code into reusable pieces.
Python Basics series: Part 1: What Every Beginner Should Know · Part 2: Variables and Data Types · Part 3: Lists and Dictionaries · Part 4: If Statement · Part 5: User Input and While Loops · Part 6: Functions · Part 7: Classes · Part 8: Files and Exceptions · Part 9: Testing Your Code
