What You Will Learn
Beginner
- How to get user input with input()
- How to convert input to numbers
- How to format output nicely
Terminalpython
# input() always returns a string
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Convert to int
age_str = input("Enter your age: ")
age = int(age_str)
print(f"Next year you will be {age + 1}.")
# Convert to float
height = float(input("Enter your height in feet: "))
print(f"You are {height} feet tall.")input() always returns string
input("Enter a number: ") returns "42" (string), not 42 (int). Always convert with int() or float() before doing math.Handling Bad Input
Terminalpython
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
except ValueError:
print("That is not a valid number!")Formatted Output
Terminalpython
# Multiple values on one line
print("Name:", "Anita", "Age:", 28)
# Name: Anita Age: 28
# Using sep and end
print("A", "B", "C", sep="-") # A-B-C
print("Loading", end="...") # Loading... (no newline)
print("Done")
# f-string formatting
price = 19.99
qty = 3
print(f"Total: ${price * qty:.2f}") # Total: $59.97Practical Exercise
Ask the user for their name: input("Name: ")
Ask for their age and convert to int
Print: f"Hi {name}, you are {age} years old"
Calculate and print their age in 10 years
Handle invalid input with try/except
Key Takeaways
- input() always returns a string - convert with int() or float().
- Always wrap int(input()) in try/except for user input.
- print() with sep= and end= for custom formatting.
- f-strings: f"Total: ${price:.2f}" for formatted output.
- sep="-" changes the separator. end="" removes the newline.
Comments
Comments
Post a Comment