← Python lessons

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() to let the user type beside it. The question is called a prompt.

colour = input("What is your favourite colour? ")
print(f"You chose {colour}.")

Run the example, type blue, and press Enter. The console conversation is:

What is your favourite colour? blue
You chose blue.

input(...) displays the prompt and waits for an answer. colour = saves that answer, and the next line displays it in a message. The typed answer is shown here because this is a conversation transcript, not an output-only example.

The space after ? separates the question from the typed answer. Keep it inside the quotation marks. You do not need to add \n to the prompt.

Keep the input call

This line only saves some text; it does not ask a question:

name = ("What is your name? ")

Write input before the parentheses to call the function and read an answer.

name = input("What is your name? ")

The prompt goes inside the parentheses; the answer returned by input() is assigned to the variable on the left of =.

Optional: put the answer on a separate line

You can also print the question first, then read the answer:

print("What is your favourite colour?")
colour = input()
print(f"You chose {colour}.")

print() ends the question with a newline, so you type underneath it:

What is your favourite colour?
blue
You chose blue.

Use a prompt inside input() when you want the question and answer on the same line. Calling input() without assigning its result still reads an answer, but does not save it for later.

Optional: two questions, two answers

Each call to input() reads one answer. Save the answers under different names if you need both later.

colour = input("What is your favourite colour? ")
animal = input("What is your favourite animal? ")
print(f"You chose {colour} and {animal}.")

Answers are text

Even if you type 12, input() gives back the string "12". You can print it straight away. To calculate with a numeric answer, you need to convert it and check that it meets the rules. Learn int(), float() and str(), conversion failures and range checks in Data Validation.

You do not need a numeric conversion when you only want to display an answer.

Your turn

Change this program to ask for a favourite animal, save the answer in animal, and print Your favourite animal is <animal>.. Put the question inside input() so the answer is typed on the same line. Leave a space at the end of the prompt. Run it twice with different answers.

colour = input("What is your favourite colour? ")
print(f"Your favourite colour is {colour}.")

See also: Variables, Printing Output, and String Formatting.


Practise this in the free Python course, where every exercise checks your code instantly.