Taking an Order (User Input)
So far, our program can talk, but it can't listen. We've used print() to display messages, but what if we want to ask the user a question and use their answer?
Getting information from the user is called user input. Think of it as your program taking a customer's order. It asks a question, waits for an answer, and then stores that answer in a variable to use later.
# The input() function displays a prompt and waits for the user to type something.
# Whatever the user types is stored in the 'user_name' variable.
# In a real program, we would use:
# order_item = input("What would you like to order? ")
# For this example, let's pretend the user typed "Coffee":
order_item = "Coffee"
# Now we can use that variable to confirm the order.
print("Great choice! So you'd like to order", order_item, ". Coming right up!")
// The prompt() function displays a pop-up box with a message (if run using browser).
// Whatever the user types is stored in the 'userName' variable.
// In a real program, we would use:
// let orderItem = prompt("Welcome to our cafe! What would you like to order? ");
// For this example, let's pretend the user typed "Coffee":
orderItem = "Coffee"
// Now we can use that variable to confirm the order.
console.log("Great choice! So you'd like to order " + orderItem + ". Coming right up!");
example output:
Welcome to our cafe! What would you like to order? Coffee
Great choice! So you'd like to order Coffee. Coming right up!
Due to limitation of the playground, we cannot run code with input on this site yet
Try copy code to run on your computer, and uncomment the input part.
For online playground:
- Python: Programiz Python Online Compiler
- JavaScript: Programiz JavaScript Online Compiler, or your browser (press F12 for most browser, paste the code and run)
User input is almost always received as a string (text) If you ask for a number and want to do math with it, you'll need to convert it first!
We'll see how to do that in our final project.
Mini-Exercise 💡
- Ask the user for their favorite food.
- Store their answer in a variable.
- Print a message that says "Oh, you like [user's favorite food]? That sounds delicious!"