input(): let your program ask a question
A program that only talks is half a conversation. input() lets it listen. It asks a question, waits for someone to type, and hands the answer to your code.
The big idea
input() shows a question, waits for an answer to be typed, and hands that answer back as text.
See it in code
The words in the parentheses are the question. Whatever gets typed is stored in the variable on the left:
bake = input("What would you like? ")
print("Coming right up:", bake)What would you like? brownie Coming right up: brownie
The program paused on the first line until an answer arrived. Then it carried on with that answer inside bake.
Ask twice and you get two answers. They arrive in the same order the questions are asked, so each needs its own variable:
bake = input("What would you like? ")
how_many = input("How many? ")
print("You ordered", how_many, bake)What would you like? cookie How many? 4 You ordered 4 cookie
how_many holds the text "4", not the number 4. input() always hands back a string, even when someone types digits.
To do math with a typed number, wrap the input() in int(). The answer goes straight from one into the other:
price_each = 2
bake = input("What would you like? ")
how_many = int(input("How many? "))
total = how_many * price_each
print(f"You ordered {how_many} {bake}")
print(f"Total: ${total}")What would you like? cookie How many? 4 You ordered 4 cookie Total: $8
int(input(...)) reads from the inside out. First the question is asked. Then int() turns the typed text into a whole number.
Asking and answering is how every interactive program works. A game listens for arrow keys. A website listens for clicks. A bakery program listens for an order.
Try it yourself
Add a third question, tip = int(input("Tip in dollars? ")), and add the tip to the total. Run it and check the math yourself.
The common mistake
Forgetting int(). Without it, how_many * price_each multiplies the text "4" by 2 and gives 44, the text written twice. Every typed number needs int() before math.
What it unlocks
Typed answers are strings, so they often need tidying first. To keep asking until the answer makes sense, use a while loop.