๐ Lesson 12: Python Input & Output – Interact with Users
Welcome to Lesson 12! Today we’ll learn how to take input from users and display output in Python. These are essential skills for making interactive programs.
⭐ What You Will Learn in This Lesson
- Display messages and values using
print() - Take user input with
input() - Convert input to numbers for calculations
- Format output neatly using concatenation, commas, and f-strings
- Create interactive programs
๐ฅ Who Is This Lesson For?
- Beginners learning Python programming
- Students building interactive scripts or small projects
- Anyone who wants to understand user input/output in Python
๐ฆ 1. Displaying Output with print()
# Print text
print("Hello, Python!")
# Print multiple items
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
# Using f-strings (Python 3.6+)
print(f"My name is {name} and I am {age} years old.")
๐งฉ 2. Taking Input with input()
# Ask user for their name
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Ask user for a number
num = input("Enter a number: ")
print("You entered:", num)
⚠ Important Note
The input() function always returns a string. To perform math, you must convert it to an integer or float:
num = int(input("Enter an integer: "))
print(num + 5)
price = float(input("Enter a price: "))
print(price * 2)
๐งฉ 3. Formatting Output
- Concatenate using
+ - Comma separation in
print() - Use f-strings for cleaner formatting
name = "Bob"
score = 95
print("Student " + name + " scored " + str(score))
print(f"Student {name} scored {score}")
๐งฉ 4. Why Input & Output Matter
- Make programs interactive
- Take user data for calculations
- Display results clearly
- Essential for projects, games, and apps
๐งช Practice
- Ask the user for their favorite color and print it in a sentence.
- Take two numbers from the user and print their sum.
- Ask for the radius of a circle and print its area.
- Use f-strings to display your name and age in a sentence.
- Take a number input and print its square and cube.
Bonus: Experiment with different ways of formatting output using f-strings, including limiting decimal places for numbers.
❌ Common Mistakes
- Forgetting that
input()always returns a string - Not converting string input to
intorfloatfor calculations - Misusing concatenation vs commas vs f-strings
❓ Frequently Asked Questions (FAQ)
1. How do I take numbers as input?
Use int() or float() to convert string input to numbers.
2. Can I combine input() and print() in one line?
Yes. For example: print("Hello, " + input("Enter your name: "))
3. Are f-strings better than concatenation?
Yes. f-strings are cleaner, easier to read, and less error-prone.
๐ What’s Next?
In the next lesson, you’ll learn about:
- Handling errors and exceptions in Python
- Making your programs more robust
- Using
try,except, andfinally
Comments
Post a Comment