Most programs are written to solve an end
user’s problem. To do so, you usually need
to get some information from the user. For a
simple example, let’s say someone wants to find
out whether they’re old enough to vote. If you write a
program to answer this question, you need to know the user’s age before
you can provide an answer. The program will need to ask the user to enter,
or input, their age; once the program has this input, it can compare it to the
voting age to determine if the user is old enough and then report the result.
In this blog you’ll learn how to accept user input so your program
can then work with it. When your program needs a name, you’ll be able
to prompt the user for a name. When your program needs a list of names,
you’ll be able to prompt the user for a series of names. To do this, you’ll use
the input() function.
You’ll also learn how to keep programs running as long as users want
them to, so they can enter as much information as they need to; then, your
program can work with that information. You’ll use Python’s while loop to
keep programs running as long as certain conditions remain true.
118 Chapter 7
With the ability to work with user input and the ability to control how
long your programs run, you’ll be able to write fully interactive programs.
How the input() Function Works
The input() function pauses your program and waits for the user to enter
some text. Once Python receives the user’s input, it stores it in a variable to
make it convenient for you to work with.
For example, the following program asks the user to enter some text,
then displays that message back to the user:
name = input("Please enter your name: ")
print("Hello, " + name + "!")
Output
Please enter your name: Prasanna
Hello, Prasanna!
Using int() to Accept Numerical Input
When you use the input() function, Python interprets everything the user
enters as a string. We can resolve this issue by using the int() function, which tells
Python to treat the input as a numerical value. The int() function converts a string representation of a number to a numerical representation,
as shown here:
height = int(input("How tall are you, in inches? "))
if height >= 36:
print("\nYou're tall enough to ride rollercoaster!")
else:
print("\nYou'll be able to ride when you're a little older.")
The Modulo Operator
A useful tool for working with numerical information is the modulo operator (%),
which divides one number by another number and returns the remainder.
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.")
Output
Enter a number, and I'll tell you if it's even or odd: 42
The number 42 is even.
Introducing while Loops
![Python While Loops - WTMatter](https://wtmatter.com/wp-content/uploads/2020/01/Python-While-Loops.png)
The for loop takes a collection of items and executes a block of code once
for each item in the collection. In contrast, the while loop runs as long as,
or while, a certain condition is true.
The while Loop in Action
You can use a while loop to count up through a series of numbers. For
example, the following while loop counts from 1 to 5:
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
We can make the copycat.py program run as long as the user wants by putting
most of the program inside a while loop. We’ll define a quit value and then
keep the program running as long as the user has not entered the quit value:
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)
Output
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit
Using a Flag
In the previous example, we had the program perform certain tasks while
a given condition was true. But what about more complicated programs in
which many different events could cause the program to stop running?
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. We
can write our programs so they run while the flag is set to True and stop running when any of several events sets the value of the flag to False. As a result,
our overall while statement needs to check only one condition: whether or
not the flag is currently True. Then, all our other tests (to see if an event has
occurred that should set the flag to False) can be neatly organized in the rest
of 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, regardless of the results of any conditional test, use the break statement.
The break statement directs the flow of your program; you can use it to control which lines of code are executed and which aren’t, so the program only
executes code that you want it to, when you want it to.
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
Output
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) New York
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit
Using continue in a Loop
Rather than breaking out of a loop entirely without executing the rest of its
code, you can use the continue statement to return to the beginning of the
loop based on the result of a conditional test. For example, consider a loop
that counts from 1 to 10 but prints only the odd numbers in that range:
current_number = 0
while current_number < 10:
u
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
Output
1
3
5
7
9
Avoiding Infinite Loops
Every programmer accidentally writes an infinite while loop from time
to time, especially when a program’s loops have subtle exit conditions. I will show you an example so that you can avoid it.
# This loop runs forever!
x = 1
while x <= 5:
print(x)
Here, you forgot to increment the value of x inside loop.
Using a while Loop with Lists and Dictionaries
So far, we’ve worked with only one piece of user information at a time. We
received the user’s input and then printed the input or a response to it.
The next time through the while loop, we’d receive another input value
and respond to that. But to keep track of many users and pieces of information, we’ll need to use lists and dictionaries with our while loops.
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.
Using while loops with lists and dictionaries allows you to collect, store, and
organize lots of input to examine and report on later.
Moving Items from One List to Another
Consider a list of newly registered but unverified users of a website. After
we verify these users, how can we move them to a separate list of confirmed
users? One way would be to use a while loop to pull users from the list of
unconfirmed users as we verify them and then add them to a separate list of
confirmed users. Here’s what that code might look like:
# Start with users that need to be verified,
users.py
# 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("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
In Chapter 3 we used remove() to remove a specific value from a list. The
remove() function worked because the value we were interested in appeared
only once in the list. But what if you want to remove all instances of a value
from a list?
Say you have a list of pets with the value 'cat' repeated several times. To
remove all instances of that value, you can run a while loop until 'cat' is no
longer in the list, as shown here:
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
You can prompt for as much input as you need in each pass through a while
loop. Let’s make a polling program in which each pass through the loop
prompts for the participant’s name and response. We’ll store the data we
gather in a dictionary, because we want to connect each response with a
particular user:
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(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 ---
Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali.
Conclusion
In this blog you learned how to use input() to allow users to provide
their own information in your programs. You learned to work with both
text and numerical input and how to use while loops to make your programs
run as long as your users want them to. You saw several ways to control the
flow of a while loop by setting an active flag, using the break statement, and using the continue statement. You learned how to use a while loop to move
items from one list to another and how to remove all instances of a value
from a list. You also learned how while loops can be used with dictionaries.
Post a Comment
Let's make it better!
Comment your thoughts...