Looping¶
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 chapter 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.
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 assigns that input to 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:
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
Tell me something, and I will repeat it back to you: I am a student I am a student
The input() function takes one argument: the prompt, or instructions, that we want to display to the user so they know what to do. In this example, when Python runs the first line, the user sees the prompt Tell me something, and I will repeat it back to you: . The program waits while the user enters their response and continues after the user presses ENTER. The response is assigned to the variable message, then print(message) displays the input back to the user:
Writing Clear Prompts¶
Each time you use the input() function, you should include a clear, easy-to-follow prompt that tells the user exactly what kind of information you’re looking for. Any statement that tells the user what to enter should work. For example:
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
Please enter your name: Zhanchao Yang Hello, Zhanchao Yang!
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}!")
If you tell us who you are, we can personalize the messages you see. What is your first name? Zhanchao Yang Hello, Zhanchao Yang!
This example shows one way to build a multi-line string. The first line assigns the first part of the message to the variable prompt. In the second line, the operator += takes the string that was assigned to prompt and adds the new string onto the end.
The prompt now spans two lines, again with space after the question mark for clarity:
Using int() to Accept Numerical Input¶
When you use the input() function, Python interprets everything the user enters as a string. Consider the following interpreter session, which asks for the user’s age:
age = input("How old are you? ")
age = int(age)
age
How old are you? 8
8
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 48:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
How tall are you, in inches? 88 You're tall enough to ride!
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:
4%3
1
6%3
0
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")
Enter a number, and I'll tell you if it's even or odd: 6 The number 6 is even.
INTRODUCING WHILE LOOPS¶
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
1 2 3 4 5
Please do not design a program that never end. It will make the user shutdown the program, Example:
# this program will run and never stop unless the user shutdown
#while current_number >= 1:
# print(current_number)
# current_number += 1
# method to solve the problem
while current_number >= 1: #best to do condition there
print(current_number)
current_number += 3
if current_number >50:
break
6 9 12 15 18 21 24 27 30 33 36 39 42 45 48
current_number = 1
while current_number <50:
print(current_number)
current_number += 3
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49
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 = 1
while current_number <=100:
if current_number % 3 ==0:
print("You win!")
else:
print(f"{current_number}, is not the number we want.")
current_number += 3
1, is not the number we want. 4, is not the number we want. 7, is not the number we want. 10, is not the number we want. 13, is not the number we want. 16, is not the number we want. 19, is not the number we want. 22, is not the number we want. 25, is not the number we want. 28, is not the number we want. 31, is not the number we want. 34, is not the number we want. 37, is not the number we want. 40, is not the number we want. 43, is not the number we want. 46, is not the number we want. 49, is not the number we want. 52, is not the number we want. 55, is not the number we want. 58, is not the number we want. 61, is not the number we want. 64, is not the number we want. 67, is not the number we want. 70, is not the number we want. 73, is not the number we want. 76, is not the number we want. 79, is not the number we want. 82, is not the number we want. 85, is not the number we want. 88, is not the number we want. 91, is not the number we want. 94, is not the number we want. 97, is not the number we want. 100, is not the number we want.
current_number = 1
while current_number <=100:
if current_number % 5 ==0:
print("You win!")
else:
print(f"{current_number}, is not the number we want.")
current_number += 3
1, is not the number we want. 4, is not the number we want. 7, is not the number we want. You win! 13, is not the number we want. 16, is not the number we want. 19, is not the number we want. 22, is not the number we want. You win! 28, is not the number we want. 31, is not the number we want. 34, is not the number we want. 37, is not the number we want. You win! 43, is not the number we want. 46, is not the number we want. 49, is not the number we want. 52, is not the number we want. You win! 58, is not the number we want. 61, is not the number we want. 64, is not the number we want. 67, is not the number we want. You win! 73, is not the number we want. 76, is not the number we want. 79, is not the number we want. 82, is not the number we want. You win! 88, is not the number we want. 91, is not the number we want. 94, is not the number we want. 97, is not the number we want. You win!
Avoiding Infinite Loops¶
Every while loop needs a way to stop running so it won’t continue to run forever. For example, this counting loop should count from 1 to 5:
x = 1
while x <= 5:
print(x)
x += 1
1 2 3 4 5
# # This loop runs forever!
# x = 1
# while x <= 5:
# print(x)
Letting the User Choose When to Quit¶
We can make the parrot.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:
while True:
number = input("Enter a number, and I'll tell you if it's even or odd: ")
if number == 'quit':
break
number = int(number)
if number % 2 == 0:
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")
Enter a number, and I'll tell you if it's even or odd: 2 The number 2 is even. Enter a number, and I'll tell you if it's even or odd: 3 The number 3 is odd. Enter a number, and I'll tell you if it's even or odd: 3 The number 3 is odd. Enter a number, and I'll tell you if it's even or odd: 0 The number 0 is even. Enter a number, and I'll tell you if it's even or odd: quit
while True:
number = input("Enter a number, and I'll tell you if it's even or odd: ")
if number == 'quit':
break
try:
number = int(number)
except:
print('Please enter a number.')
continue
if number % 2 == 0:
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")
Enter a number, and I'll tell you if it's even or odd: kkk Please enter a number. Enter a number, and I'll tell you if it's even or odd: jjj Please enter a number. Enter a number, and I'll tell you if it's even or odd: 8 The number 8 is even. Enter a number, and I'll tell you if it's even or odd: quit
Finish¶
References¶
- Matthes, Eric (2022). Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming. No Starch Press. ISBN: 978-1593279288. (Publisher website)
- Dr.Qiusheng Wu online lecture