120 likes | 152 Views
CS111 Intro to Programming. Day 20: While Loops and User Input. Learning Objectives. Understand how to work with while loops Understand how to work with user input Use while loops to prompt a user to “Play Again?”. User Input. Console Input.
E N D
CS111 Intro to Programming Day 20: While Loops and User Input
Learning Objectives • Understand how to work with while loops • Understand how to work with user input • Use while loops to prompt a user to “Play Again?”
Console Input Python provides the input() function to read user input from the console. The input() function displays a message to the user and returns a String that contains the user’s response. name = input(“Please enter your name: ”)
Console Input Example Add items to a List # Create an empty grocery list groceryList = [] # Prompt the user for an item to add to the list item = input(“Please enter an item: ”) # Add the item to the list groceryList.append(item) Download
Console Input Example Simple Integer Calculator # Prompt the user for two numbers num1 = input(“Please enter the first number: ”) num2 = input(“Please enter the second number: ”) # Calculate the sum of the two numbers sum = int(num1) + int(num2) # Display the result print(“The sum of ” + num1 + “ and ” + num2 + “ is ” + str(sum)) Download
Conditional Looping A while-loop will execute a block of code repeatedly as long as the specified condition remains true. While loops are useful for validating user input. While loops are useful for repeating an operation when the number of loop iterations is not known ahead of time.
While Loop Syntax while condition: # statements # other code A boolean expression. Continue executing code outside loop code block. Execute repeatedly while condition remains true. Indented Code Block
While Loop Example - Add items to List # Item Entry Loop done = False while done == False: # Prompt the user for an item to add to the list item = input(“Please enter an item or done when finished: ”) # Check if user is done entering items if item.lower() == “done”: done = True else: # Add the item to the list groceryList.append(item) Download
M.A.S.H. Game Example Revisited Download