Asking a question
So far our programs always print the same thing. input() lets the program ask the user something and wait for an answer.
name = input("What is your name? ")
print("Nice to meet you,", name)Output (when you type Priya)
What is your name? Priya Nice to meet you, Priya
Here is what happens step by step:
- Python shows the message
What is your name?and waits. - The user types
Priyaand presses Enter. input()gives back"Priya", which is stored inname.
Tip: Put a space at the end of the question, like
"What is your name? ", so the answer isn't squashed against the question.
input() always gives text
Whatever the user types – even a number – input() gives you a string. Look:
number = input("Type a number: ")
print(number + number)Output (when you type 7)
Type a number: 7 77
We got 77, not 14! The two strings "7" were joined together.
Turning input into a number
Wrap input() in int() (or float() for decimals):
number = int(input("Type a number: "))
print(number + number)Output (when you type 7)
Type a number: 7 14
height = float(input("Your height in metres: "))
print("In centimetres that is", height * 100)Output (when you type 1.65)
Your height in metres: 1.65 In centimetres that is 165.0
Remember:
int(input())for whole numbers,float(input())for decimal numbers, plaininput()for text.
Input in the coding challenges
In the challenges, your program gets its input automatically, one line at a time, as if a user typed it. Use input() without a question inside, because the checker compares everything you print, and an extra question would make the output wrong.