跳到主要内容

User Input and while Loops

Most programs are written to solve an end user's problem. To do so, you usually need to get some information from the user. In this chapter, you'll learn how to accept user input so your program can work with it, and you'll learn how to keep programs running as long as users want them to.

How the input() Function Works

The input() function pauses your program and waits for the user to enter some text:

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

Output:

Tell me something, and I will repeat it back to you: Hello everyone!
Hello everyone!

Writing Clear Prompts

Each time you use the input() function, you should include a clear, easy-to-follow prompt:

name = input("Please enter your name: ")
print(f"\nHello, {name}!")

Sometimes you'll want to write a prompt that's longer than one line:

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print(f"\nHello, {name}!")

Using int() to Accept Numerical Input

When you use the input() function, Python interprets everything the user enters as a string:

age = input("How old are you? ")
print(type(age)) # <class 'str'>

age = int(age)
print(type(age)) # <class 'int'>

The Modulo Operator

The modulo operator (%) divides one number by another number and returns the remainder:

print(4 % 3)  # 1
print(5 % 3) # 2
print(6 % 3) # 0

When one number is divisible by another number, the remainder is 0, so the modulo operator always returns 0. This is useful for determining if a number is even or odd.

Introducing while Loops

The for loop takes a collection of items and executes a block of code once for each item. In contrast, a while loop runs as long as, or while, a certain condition is true.

The while Loop in Action

current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1

Output:

1
2
3
4
5

Letting the User Choose When to Quit

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

message = ""
while message != 'quit':
message = input(prompt)
print(message)

This program works, but it prints 'quit' as a message. A simple fix is to test the message before printing it:

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

message = ""
while message != 'quit':
message = input(prompt)

if message != 'quit':
print(message)

Using a Flag

For a program that should run only as long as many conditions are true, you can define one variable that determines whether or not the entire program is active. This variable, called a flag, acts as a signal to the program:

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

active = True
while active:
message = input(prompt)

if message == 'quit':
active = False
else:
print(message)

Using break to Exit a Loop

To exit a while loop immediately without running any remaining code in the loop, use the break statement:

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

while True:
message = input(prompt)

if message == 'quit':
break
else:
print(message)

Using continue in a Loop

Rather than breaking out of a loop entirely, you can use the continue statement to return to the beginning of the loop:

current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue

print(current_number)

Output:

1
3
5
7
9

Avoiding Infinite Loops

Every while loop needs a way to stop running so it won't continue to run forever:

# This will run forever!
x = 1
while x <= 5:
print(x)
# Missing: x += 1
注意

If your program gets stuck in an infinite loop, press Ctrl+C or close the terminal window displaying your program's output.

Using a while Loop with Lists and Dictionaries

A for loop is effective for looping through a list, but you shouldn't modify a list inside a for loop because Python will have trouble keeping track of the items in the list. To modify a list as you work through it, use a while loop.

Moving Items Between Lists

# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()

print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)

# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())

Output:

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice

Removing All Instances of Specific Values from a List

The remove() function removes only the first occurrence of a value. You can use a while loop to remove all occurrences:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
pets.remove('cat')

print(pets)

Output:

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

Filling a Dictionary with User Input

responses = {}

# Set a flag to indicate that polling is active.
polling_active = True

while polling_active:
# Prompt for the person's name and response.
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")

# Store the response in the dictionary.
responses[name] = response

# Find out if anyone else is going to take the poll.
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == 'no':
polling_active = False

# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")

Output:

What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/no) yes

What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/no) no

--- Poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thumb.

Summary

In this chapter you learned how to:

  • Use input() to let users provide information
  • Work with both text and numerical input
  • Use while loops to keep programs running as long as certain conditions remain true
  • Control the flow of your while loops using flags, the break statement, and the continue statement
  • Move items between lists using while loops
  • Remove all instances of a value from a list
  • Fill dictionaries with user input

Knowing how to process user input and control how long your programs run will help you write fully interactive programs.