Getting Input from the User
Let your program talk back and forth with the person using it
input() your program can ask a question, wait for the person to type an answer, and use that answer. That is how a program becomes interactive.
- read what the user types with
input(), - understand that
input()always gives you text, - turn that text into numbers with
int()andfloat(), - write a small program that asks questions and does math with the answers.
1. The input() function
The built-in function input() pauses your program and waits for the person to type something and press Enter. Whatever they type is handed back to your program so you can save it in a variable.
You can put a short message, called a prompt, inside the round brackets. It is shown on the screen so the user knows what to type.
name = input("What is your name? ")
print("Hello, " + name + "!")Expected output (the user typed "Sara"):
What is your name? Sara
Hello, Sara!
The prompt "What is your name? " appears, the program waits, and the word the user types is stored in the variable name. Then we use it in print().
2. input() always gives you TEXT
This is the most important idea in this lesson. No matter what the user types, input() always hands it back as a string (text). Even if they type digits like 10, Python treats it as the text "10", not the number 10.
age = input("How old are you? ")
print(type(age))Expected output (the user typed "10"):
How old are you? 10
<class 'str'>
The message <class 'str'> is Python's way of saying "this is a string". So this code breaks, because you cannot add the number 1 to a piece of text:
age = input("How old are you? ")
print(age + 1)Expected output (an error!):
How old are you? 10
TypeError: can only concatenate str (not "int") to str