Beginner âĸ Python
User Input
â Asking a Question with input()
The input() function lets your program ask the user a question and wait for them to type an answer. The text inside the brackets is the question shown on the screen. The program pauses until the user types something and presses Enter. If you type Sam:
name = input("What is your name? ")
print("Hello, " + name + "!")What is your name? Sam Hello, Sam!
đ Everything in User Input
Learn how to ask the user questions with input(), save their answers, turn answers into numbers, and build fun interactive programs. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.
â Asking a Question with input()
The input() function lets your program ask the user a question and wait for them to type an answer. The text inside the brackets is the question shown on the screen. The program pauses until the user types something and presses Enter. If you type Sam:
name = input("What is your name? ") print("Hello, " + name + "!")đĻ Storing and Using Answers
Whatever the user types is saved in a variable, so you can use it again and again. You can ask more than one question and store each answer in its own variable. Then you can mix the answers into a message with an f-string. If you type blue and then pizza:
colour = input("Favourite colour? ") food = input("Favourite food? ") print(f"You like {colour} things and eating {food}!")đ¤ Input Is Always Text
input() always gives back a string, even if the user types a number. That means "5" + "5" joins the text together and makes "55" instead of adding. To do math, we need to change the text into a number first. If you type 5:
number = input("Type a number: ") print(number + number)đĸ Turning Input into Numbers
The int() function turns text into a whole number, like 7 or 12. The float() function turns text into a decimal number, like 2.5. Once the answer is a number, you can add, subtract, and multiply it. If you type 7 and then 2.5:
apples = int(input("How many apples? ")) print(apples + 3) price = float(input("Price of one apple? ")) print(apples * price)đ Building a Greeter
Now we can combine input() with if statements to make a program that reacts to the user. The program checks what the user typed and gives a different reply. This is how games and apps respond to you! If you type Zoe and then yes:
name = input("Name: ") happy = input("Are you happy today? (yes/no) ") if happy == "yes": print(f"Awesome, {name}! Keep smiling!") else: print(f"Cheer up, {name}! Tomorrow is a new day.")đ Making an Age Calculator
Let's build a small calculator that works out ages. We ask for the user's age, turn it into a number with int(), and then do some math. The program can tell you how old you will be in the future. If you type 9:
age = int(input("How old are you? ")) print(f"In 5 years you will be {age + 5}.") print(f"You have lived about {age * 365} days!")
