Input and Output - Getting User Input
In programming, interaction is key. We need to get information FROM users and show information TO users. Python makes this incredibly easy with the input() and print() functions.
Getting User Input
The input() function allows your program to pause and wait for the user to type something. It always returns what the user types as a string.
name = input("What is your name? ")
print("Hello, " + name)
What is your name? Alice
Hello, Alice
Input is Always a String
Remember: input() always returns a string, even if the user types a number. If you want to use it as a number, you must convert it.
age_text = input("How old are you? ")
age = int(age_text) # Convert to integer
print("Next year you will be", age + 1)
How old are you? 25
Next year you will be 26
Converting Input to Different Types
You can convert input to different data types:
- int() - Converts to integer
- float() - Converts to floating-point number
- str() - Converts to string (already a string)
height = float(input("Enter your height in meters: "))
print("Your height is", height, "meters")
Enter your height in meters: 1.75
Your height is 1.75 meters
Formatting Output with f-strings
Python 3.6+ introduced f-strings (formatted string literals), which make it easy to insert variables into strings.
age = 30
print(f"My name is {name} and I am {age} years old.")
My name is Bob and I am 30 years old.
Notice the f before the quotes and the curly braces {} around variable names.
Practice Challenge
Your Task: Create a program that:
- Asks the user for their name
- Asks for their age
- Asks for their favorite number
- Prints a message using all three pieces of information with an f-string
- Calculates and prints what their age will be in 10 years
Hint: Remember to convert the age to an integer for the calculation!
Key Takeaways
- input() gets information from the user
- input() always returns a string
- Use int() or float() to convert input to numbers
- F-strings make it easy to format output with variables
- Put an f before the quotes: f"text {variable}"
0 Comments