Input
π¨π Technique Card: Getting Input From the User in Python (practical)
π What Youβll Learn
How to ask the user questions in your Python program and use their answers in creative ways. You'll also learn how to turn the input into numbers when needed.
π§βπ» Why Is This Useful?
Sometimes you want your program to feel interactive, like:
- βWhatβs your name?β
- βHow old are you?β
- βPick a number between 1 and 10!β
Using input()
lets your program talk to the user and get answers back.
π§ͺ Try It Out: Basic Input
name = input("What is your name? ")
print("Hello, " + name + "!")
β This asks the user for their name and then says hello.
π§ Remember: input()
always gives you a string
That means even if you type a number, Python thinks it's text.
age = input("How old are you? ")
print(age + 5) # β οΈ This gives an error!
π§ Converting Input to a Number
If you want to use numbers (like adding or comparing), youβll need to cast the string to a number using int()
or float()
.
age = int(input("How old are you? "))
print("Next year, you'll be", age + 1)
Hereβs what happens:
input()
asks the questionint(...)
changes the answer from text to a number
You could also use:
age = input("How old are you? ")
age = int(age)
print("Next year, you'll be ", age + 1)
π§ͺ Try This Challenge
number = int(input("Pick a number: "))
print("Double your number is", number * 2)
π You Might Need This Too
Sometimes you want a number with decimals, not just whole numbers. Use float()
instead:
temperature = float(input("Whatβs the temperature today? "))
print("Tomorrow might be", temperature + 1.5)
β οΈ Be Careful!
If the user types something that isnβt a number, Python will give an error!
Youβll learn how to fix that with error handling in other technique cards.
π‘ Top Tips
- Always use
input()
for asking questions. - Remember: It gives back a string (text), even if it looks like a number.
- Use
int()
for whole numbers,float()
for decimal numbers. - Put
input()
inside the brackets ofint()
orfloat()
when needed.