User Input & Output
Learn how to get input from users with input() and format output with print(). Understanding I/O is crucial for building interactive programs.
Input and Output
- input(prompt) — Gets text input from the user (always returns string)
- print() — Displays output. Can take multiple arguments separated by commas
- sep= — Change separator between print arguments (default: space)
- end= — Change end character (default: newline \n)
- f-strings — f"Hello, {name}!" — embed variables in strings
- format() — "Hello, {}!".format(name) — older formatting
- % formatting — "Hello, %s!" % name — legacy C-style formatting
Input & Output Code
# Output with print()
print("Hello!")
print("Name:", "Alice", "Age:", 25)
print("A", "B", "C", sep="-") # A-B-C
print("Loading", end="...") # no newline
print("Done!") # Loading...Done!
# f-strings (recommended!)
name = "Alice"
age = 25
print(f"Hello, {name}! You are {age} years old.")
print(f"Next year you'll be {age + 1}.")
print(f"Price: ${9.99:.2f}") # Price: $9.99
# Input (always returns a string)
# Uncomment these to test interactively:
# name = input("Enter your name: ")
# age = int(input("Enter your age: "))
# print(f"Hello {name}, you are {age} years old!")
# Simulated input for demo
name = "Alice"
age = 25
print(f"\nHello {name}, you are {age} years old!")Tip
Tip
f-strings are the recommended way to format output in modern Python. Use f'{value:.2f}' for 2 decimal places, f'{value:>10}' for right-alignment, f'{value:,}' for thousand separators.
Everything in Python is an object — use type() to check
Common Mistake
Warning
Concatenating strings and numbers directly fails: 'Age: ' + 25 raises TypeError. Use f-strings f'Age: {25}' or convert: 'Age: ' + str(25). f-strings handle this automatically.
Practice Task
Note
I/O practice: (1) Print your name using 3 different formatting methods: +, .format(), f-string. (2) Use sep='-' and end='!' in print(). (3) Format a price as $XX.XX using f'{price:.2f}'.
Quick Quiz
Key Takeaways
- Learn how to get input from users with input() and format output with print().
- input(prompt) — Gets text input from the user (always returns string)
- print() — Displays output. Can take multiple arguments separated by commas
- sep= — Change separator between print arguments (default: space)