Code:[ZachxPKU/Python Crash Course]
Python Crash Course
Chapter 7 User input and while loops
7.1 How the input() function works
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
7.1.1 Writing clear prompts
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
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}!")
7.1.2 Using int() to accept numerical input
age = input("How old are you? ")
age
age = int(age)
age >= 18
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.")
7.1.3 The modulo operator
5 % 2
6 % 3
8 % 3
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.")
TRY IT YOURSELF
- rental_car.py
- rental_car.py
- multiples_of_ten.py
7.2 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.
7.2.1 The while loop in action
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
7.2.2 Letting the user choose when to quit
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
7.2.3 Using a flag
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)
7.2.4 Using break to exit a loop
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(f"I'd love to go to {city.title()}!")
7.2.5 Using continue in a Loop
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
7.2.6 Avoiding Infinite Loops
x = 1
while x <= 5:
print(x)
x += 1
# x = 1
# while x <= 5:
# print(x)
TRY IT YOURSELF
- pizza_toppings.py
- movie_tickets.py
- infinity.py
7.3 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. Using while loops with lists and dictionaries allows you to collect, store, and organize lots of input to examine and report on later.
7.3.1 Moving items from one list to another
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
7.3.2 Removing all instances of specific values from a list
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
7.3.3 Filling a dictionary with user input
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
TRY IT YOURSELF
- deli.py
- no_pastrami.py
- dream_vacation.py