User Input Handling
The input() function captures user-provided data, displaying an optional prompt. To enhance clarity, separate prompts from input areas using spaces.
user_input = input("What's for dinner tonight? ")
print(user_input)
For multi-line prompts, store the text in a variable first:
prompt_text = "Share your identity to view personalized info. "
prompt_text += "\nWhat's your full name? "
user_name = input(prompt_text)
Convert string inputs to numerical values using int():
age_str = input("How old are you? ") # input() returns a string
user_age = int(age_str)
print(user_age > 18)
Determine even/odd numbers with the modulus operator (%), which returns division remainders:
num_str = input("Enter a number: ")
num = int(num_str)
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
While Loop Fundamentals
While loops execute repeatedly untill a condition becomes false, unlike for loops that iterate over collections.
Basic Counting Loop
count = 1
while count < 5:
print(count)
count += 1
Termination via Condition Test
Exit when user enters a specific value:
topping_prompt = "Add a pizza topping (or 'none' to finish): "
user_choice = ""
while user_choice != "none":
user_choice = input(topping_prompt)
if user_choice != "none":
print(f"Adding {user_choice} to your pizza.")
Flag-Controlled Loop
Use a boolean flag to manage loop state:
topping_prompt = "Add a pizza topping (or 'none' to finish): "
is_active = True
while is_active:
choice = input(topping_prompt)
if choice == "none":
is_active = False
else:
print(f"Adding {choice} to your pizza.")
Break Statement for Early Exit
Immediately exit loops with break:
topping_prompt = "Add a pizza topping (or 'quit' to finish): "
while True:
selection = input(topping_prompt)
if selection == "quit":
break
print(f"Adding {selection} to your pizza.")
Continue Statement for Skipping Iterations
Skip remaining code in an iteration with continue:
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i) # Prints odd numbers 1-9
Avoiding Infinite Loops
Ensure loop conditions eventual become false. For accidental infinite loops, use IDE termination shortcuts (e.g., Ctrl+C).
x = 0
while x < 3: # Properly bounded to prevent infinity
print(x)
x += 1
List and Dictionary Processing
Transferring List Elements
Move items betweeen lists using pop():
order_list = ["egg sandwich", "veggie sandwich", "orleans sandwich"]
completed_orders = []
while order_list:
current_order = order_list.pop()
print(f"Preparing {current_order}")
completed_orders.append(current_order)
print("Completed orders:", completed_orders)
Removing Specific Values
Eliminate all instances of a value from a list:
order_list = ["tuna sandwich", "veggie sandwich", "tuna sandwich", "ham sandwich"]
print("Tuna sandwiches sold out!")
while "tuna sandwich" in order_list:
order_list.remove("tuna sandwich")
print("Updated orders:", order_list)
Populating Dictionaries with User Input
Collect survey responses into a dictionary:
survey_results = {}
is_polling = True
while is_polling:
participant = input("Your name: ")
destination = input("Dream vacation spot: ")
survey_results[participant] = destination
another = input("Add another participant? (yes/no): ")
if another.lower() == "no":
is_polling = False
print("\n--- Survey Results ---")
for name, place in survey_results.items():
print(f"{name}'s dream spot: {place}")