Reading Input
input() waits for someone to type an answer and press Enter. It gives your
program that answer as text. Store it in a variable so you can use it later.
Ask and answer on the same line
Put the question inside input(). The question is called a prompt, and
the user types beside it.
colour = input("What is your favourite colour? ")print("You chose", colour)Run the example, type blue, and press Enter. The console shows:
What is your favourite colour? blue
You chose blue
colour = saves the answer. The next line prints it.
The space after ? keeps the question apart from the answer. Keep it inside
the quotation marks.
Keep the input call
Without the word input, the line only saves the question text:
name = ("What is your name? ") # wrong: never asks anything
name = input("What is your name? ") # right: asks, then saves the answer
Two questions, two answers
Each call to input() reads one answer. Save each answer under its own name.
colour = input("What is your favourite colour? ")animal = input("What is your favourite animal? ")print("You chose", colour, "and", animal)Answers are text
Even if you type 12, input() gives back the text "12", not a number.
age = input("How old are you? ")print(age + age)Type 12 and this prints 1212: + joins two pieces of text. To do maths
with an answer, convert it first — see
Data Validation.
See also: Variables, Printing Output.
Your turn
Ask What is your favourite animal? with input() and save the answer in
animal. Then print Your favourite animal is followed by the saved answer.
Keep the space at the end of the prompt. Run your program twice with different
answers to check that the message uses what you typed.
# ask the question and save the answer in animal# print "Your favourite animal is" and animalFor example, typing cat should produce:
What is your favourite animal? cat
Your favourite animal is cat
Optional practice: answers are text
Pretend input() gave back "12". Print age joined to itself, then print
You are 12.
1212 You are 12
age = "12"# add two prints: age + age, then "You are" and ageAdvanced reading
- Cleaning typed answers — ask on a separate line, trim spaces, ignore case and split one answer into several.