User Input and Display β¨οΈ¶
Mentor's Note: A program that doesn't take input is like a radioβit only talks. A program that takes input is like a conversation! π‘
π The Scenario: The Magic Mirror πͺ¶
Imagine you have a magic mirror that repeats whatever you say.
- The Logic: You give it a word (Input). π¦
- The Result: It shows you the word back (Output). β
π» Implementation: The Greeting Lab¶
# π Scenario: Greeting a User
# π Action: Taking input and displaying it
# 1. Taking String Input (Text) π
name = input("Enter your name: ") # Prompts user and reads input as a string
print("Hello,", name + "!")
# 2. Taking Integer Input (Numbers) π’
# input() always returns a string, so we MUST convert it to an integer
number_str = input("Enter your favorite number: ")
number = int(number_str) # Convert the string to an integer
print(f"Your favorite number is: {number}")
π Key Concepts¶
input(): This function displays a message (the prompt) and waits for the user to type something and press Enter.- Always a String: Everything you type into
input()is treated as text. If you want a number, you must convert it usingint()orfloat(). f-strings: Usingf"Text {variable}"is the modern, professional way to combine text and data in Python.
π§ Step-by-Step Logic¶
- Start π
- Prompt the user: "Enter your name: ".
- Wait for the user to type and press Enter.
- Store that value in the variable
name. - Display "Hello, " followed by the
name. - End π
π― Practice Lab π§ͺ¶
Task: Age Calculator
Task: Ask the user for their birth year, calculate their age (2026 - birth_year), and print it.
Hint: Don't forget to use int() for the year! π‘
Quick Quiz¶
Quick Quiz
If you type 10 into an input() prompt, what is the data type of the result?
- [ ] int
- [x] str
- [ ] float
- [ ] boolean
Explanation: The input() function always returns a string (str), even if you type a number. You must use int(input()) to get an integer.