🐍
Input and Output
Beginner
60 XP
25 min
Lesson Content
Input and Output: Interacting with Users
So far, we've only displayed output. Now let's learn how to get input from users and create interactive programs!
The input() Function
The input() function reads text from the user. It always returns a string, even if the user types a number.
# Get user input
name = input("Enter your name: ")
print("Hello,", name)
# Input with a prompt
age = input("How old are you? ")
print("You are", age, "years old")Converting Input Types
Since input() always returns a string, you need to convert it for numbers:
# Get number input (convert to int)
age = int(input("Enter your age: "))
print("Next year you'll be", age + 1)
# Get float input
price = float(input("Enter price: "))
total = price * 1.1 # Add 10% tax
print("Total with tax:", total)String Formatting
Multiple ways to format strings in Python:
1. Using f-strings (Recommended)
name = "Alice"
age = 25
message = f"My name is {name} and I'm {age} years old"
print(message) # My name is Alice and I'm 25 years old2. Using .format()
name = "Alice"
age = 25
message = "My name is {} and I'm {} years old".format(name, age)3. Using % formatting
name = "Alice"
age = 25
message = "My name is %s and I'm %d years old" % (name, age)Multiple Values in print()
You can print multiple values separated by commas:
name = "John"
age = 22
city = "New York"
# Print with commas (adds spaces automatically)
print(name, age, city) # John 22 New York
# Print with custom separator
print(name, age, city, sep=" - ") # John - 22 - New York
# Print without newline
print("Hello ", end="")
print("World") # Hello World (on same line)Complete Example
# Interactive program
print("=== User Registration ===")
name = input("Enter your name: ")
age = int(input("Enter your age: "))
email = input("Enter your email: ")
print(f"\nWelcome, {name}!")
print(f"Age: {age}")
print(f"Email: {email}")Example Code
Create a program that asks for the user's name and age, then greets them.
# Create an interactive greeting program
# Ask for name and age, then display a personalized message
# Get user's name
name = input("What's your name? ")
# Get user's age (convert to int)
age = int(input("How old are you? "))
# Print personalized greeting using f-string
print(f"Hello, {name}! You are {age} years old.")
print(f"Next year you'll be {age + 1}!")Expected Output:
Hello, Student! You are 20 years old. Next year you'll be 21!
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code