Asking the user: input()
So far our programs only talked. Now they'll listen: ask the user a question, and turn their answer into a number.
1. Asking a question
input is how a program asks the user something. It shows a question on the screen, waits for the user to type an answer and press Enter, and then hands that answer to your program.
name = input("Your name: ")
print("Hello", name)Your name: Alex Hello Alex
input( )Shows a question, waits, and gives back what the user typed."Your name: "The question, inside the round brackets, in quotes.name =Whatever they type, say Alex, becomes the value, and name is stuck on it.When it asks, the user types: Alex
Press Run
2. input always gives text
Here's the part that surprises everyone. input always gives back text. Even if you type 26, Python says class str. Because input doesn't know you meant a number. It just hands over the letters you typed.
age = input("Your age: ")
print(type(age))Your age: 26 <class 'str'>
3. Turning text into numbers
Python has a tool for that called int. int takes text like 26 and turns it into a real whole number. You wrap it around input.
age = int(input("Your age: "))
print(type(age))Your age: 26 <class 'int'>
int( )Turns text into a whole number.))Two round brackets opened, so two must close: one for input, one for int.float does the same, but for decimal numbers like a price.
price = float(input("Price: "))
print(type(price))Price: 49.5 <class 'float'>
And it works the other way too: str turns a number into text.
4. Two mistakes to watch
age = int(input("Your age: "))age = int(input("Your age: "))5. Where it's used
Anywhere a program needs something from you: an ATM asking the amount, a form asking your age, a chatbot waiting for your message.