Getting User Input

Getting user input is like asking someone a question and waiting for their answer. You're the program asking, and the user is answering.
The `input()` function is your program's way of communicating with the user. It displays a prompt (optional), then pauses the program and waits for the user to type something and press Enter. Whatever the user types is returned as a **string** (text). This makes programs interactive – they can react differently based on what the user enters.

**Basic syntax:**
```python
variable = input("Prompt message: ")
```
The prompt is optional, but it's good practice to tell the user what to type. Always add a space at the end of the prompt so the user's cursor appears after a space.

**Important: `input()` always returns a string**
Even if the user types a number, `input()` gives you a string. Example: `age = input("Enter age: ")` – if the user types `25`, `age` becomes `"25"` (string), not `25` (integer).

**Converting input to numbers:**
To use numbers for math, you must convert the string to a number:
- `int()` – converts to integer (whole number). Example: `age = int(input("Age: "))`
- `float()` – converts to decimal number. Example: `price = float(input("Price: "))`

If the user types something that cannot be converted (e.g., letters when a number is expected), your program will crash with a `ValueError`. In future lessons, you'll learn to handle such errors with `try`/`except`.

**Reading multiple inputs:**
You can call `input()` multiple times to get multiple pieces of data. Each call waits for a new line.

**Empty input:**
If the user presses Enter without typing anything, `input()` returns an empty string (`""`). You can check for this with `if user_input == ""`.

**Real‑world uses:**
- Text‑based games (choose your own adventure)
- Data entry forms (collect name, age, address)
- Simple calculators
- Search interfaces
- Configuration tools

**Common mistakes:**
- Forgetting to convert a number input before doing math – results in string concatenation instead of addition (e.g., `"10" + "5"` → `"105"`).
- Assuming the user will always enter valid data – always consider validation.
- Using `input()` without a prompt – the user won't know what to type.
- Not stripping whitespace – use `.strip()` to remove accidental spaces: `name = input("Name: ").strip()`

**Best practices:**
- Always provide clear, specific prompts.
- Convert inputs to the desired type immediately, or store the raw input and convert later.
- Use `.strip()` to remove leading/trailing spaces.
- For yes/no questions, convert to lowercase and check the first letter: `answer = input("Continue? (y/n): ").lower().startswith('y')`

**Practice exercises:**
1. Ask the user for their name, age, and city. Print a sentence that includes all three.
2. Create a simple temperature converter: ask for Celsius, convert to Fahrenheit using `F = (C * 9/5) + 32`, and print the result.
3. Ask the user for a number, then print its square, cube, and square root (use `** 0.5` for square root).
4. Build a simple login: ask for a username and password, check if they match a hardcoded value, and print "Access granted" or "Access denied".
5. Use a loop (future lesson) to keep asking until valid input is provided.

**Example with type conversion and formatting:**
```python
# Get and convert
age_str = input("How old are you? ")
age = int(age_str)
years_to_100 = 100 - age
print(f"You will be 100 in {years_to_100} years")
```
# ========== EXAMPLE 1: Basic Input with Strings ==========
print("=== Example 1: Asking for Text ===")
name = input("What is your name? ")
print(f"Hello {name}! Nice to meet you!")

favorite_color = input("What's your favorite color? ")
print(f"Wow, {favorite_color} is a beautiful color!")
print()

# ========== EXAMPLE 2: Converting Input to Numbers (int and float) ==========
print("=== Example 2: Numeric Input and Calculations ===")
# Integer input
age_text = input("How old are you? ")
age = int(age_text)
birth_year = 2024 - age
print(f"You were born around {birth_year}")

# Float input
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
result = float(num1) + float(num2)
print(f"Sum: {result}")
print()

# ========== EXAMPLE 3: Input with Stripping and Validation ==========
print("=== Example 3: Cleaning Input and Simple Validation ===")
# Strip whitespace and convert to lowercase for consistent comparison
answer = input("Do you like Python? (yes/no): ").strip().lower()
if answer == "yes":
    print("Great! Python is awesome!")
elif answer == "no":
    print("Maybe you'll learn to love it!")
else:
    print("Please answer yes or no next time.")

# Using .isdigit() to check if input is a number
user_input = input("Enter a number (or anything else): ")
if user_input.isdigit():
    print(f"You entered the number {user_input}")
else:
    print(f"You entered text: '{user_input}'")

# Create a simple calculator with three operations
print("\nSimple Calculator:")
a = float(input("First number: "))
b = float(input("Second number: "))
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")

→ Run this code interactively