Input & Output: Talking to Your User
1 · The lesson
readA program that only does math in its head is like someone muttering to themselves. To be useful, a program needs to talk to the user (output) and listen to the user (input).
This lesson covers everything you need to make your programs interactive: print() in depth, input(), type conversion (the part that catches every beginner), and a safe pattern for handling bad input.
1. Output: print() in Depth
You've seen print() before. Here's what it can actually do.
# Pass multiple values — print joins them with a space by default print("Hello", "world", 2026) # Hello world 2026 # Change the separator between values print("apple", "banana", "cherry", sep=", ") # apple, banana, cherry # Change what's printed at the end (default is "\n", a new line) print("Loading", end="...") print("done") # Loading...done # Print to standard error instead of standard output (for warnings/errors) import sys print("Something went wrong", file=sys.stderr)
The sep and end arguments are tiny but useful — they let you control formatting without building strings manually.
2. Input: Getting Data from the User
input() is how Python listens. When the program hits an input() call, it pauses and waits for the user to type something and press Enter.
name = input("What is your name? ") print(f"Hello, {name}!")
The argument to input() is the prompt — the text shown before the user types. Always include a trailing space ("...? ") so the cursor doesn't stick to the question mark.
Note:
input()doesn't work in the browser sandbox. The Run button here will show a friendly heads-up. To tryinput(), copy the code into a local Python file and run it from a terminal.
3. The Single Most Important Rule
input()always returns a string. Always. Even if the user types42, you get the string"42".
This catches every Python beginner at least once. Watch:
# Simulating what input() returns — always a string age_text = "25" # This is what input() would give us # The naive attempt — adding 1 to a string crashes: # print(age_text + 1) # TypeError! # The fix — convert before doing math: age = int(age_text) print(f"Next year you will be {age + 1}") # Next year you will be 26
If you want a number, you must explicitly convert the string. That's what the next section is about.
4. Type Conversion: int(), float(), str(), bool()
Python gives you four conversion functions for the basic types. Each takes a value and tries to produce the matching type.
# String → integer n = int("42") print(n, type(n)) # 42 <class 'int'> # String → float (decimal) price = float("19.99") print(price, type(price)) # 19.99 <class 'float'> # Number → string score = 95 label = str(score) print(label, type(label)) # 95 <class 'str'> # Anything → boolean (uses Python's truthy/falsy rules) print(bool(0)) # False print(bool("")) # False print(bool("hello")) # True print(bool([])) # False print(bool([1, 2])) # True
The float() trick: float() accepts both ints and strings — so float("3") gives 3.0, and float(3) also gives 3.0. Handy when you don't know if the input has a decimal.
The int() trap: int("3.5") will crash. int() only parses whole-number strings. Use int(float("3.5")) if you want to truncate, or round(float("3.5")) if you want to round.
# This works: print(int("3")) # 3 print(int(3.9)) # 3 (truncates floats — no rounding) # This crashes: # print(int("3.5")) # ValueError: invalid literal for int() # This is the safe pattern: print(int(float("3.5"))) # 3 (truncates after parsing) print(round(float("3.5"))) # 4 (proper rounding)
5. The Real-World Pattern: input() + conversion
Combining everything you've learned, here's how 95% of beginner Python programs start:
# Pretend the user typed "100" at the prompt user_input = "100" # in real code: input("How much? ") # Convert immediately — don't let untyped strings spread through your code amount = float(user_input) # Now you can do math tip = amount * 0.18 total = amount + tip print(f"Tip: ${tip:.2f}") # Tip: $18.00 print(f"Total: ${total:.2f}") # Total: $118.00
The :.2f inside the f-string formats the number to 2 decimal places — perfect for money.
6. Safe Input: Handling Bad Data
What if the user types "abc" when you asked for a number? int("abc") raises a ValueError and your program crashes.
Real programs handle this gracefully with try/except (we'll cover this fully in a later lesson, but here's the pattern you'll reach for):
user_input = "not a number" # what the user might type try: amount = float(user_input) print(f"You entered: {amount}") except ValueError: print("That doesn't look like a number — please try again.")
When float() raises a ValueError, the except block catches it and we print a friendly message instead of crashing. This is the difference between a toy program and a useful one.
7. Mistakes You'll Hit
1. Forgetting to convert
# This crashes — you can't add a number to text # age = input("Age: ") + 1
Fix: always convert immediately after
input().
2. No trailing space in the prompt
# Ugly — cursor sticks to the colon name = input("Name:") # Better name = input("Name: ")
3. Using int() on a decimal string
# Crashes # int("3.5") # Works int(float("3.5"))
4. Forgetting that print() adds a newline
print("Loading") print("done") # Two lines. If you want them joined: print("Loading", end="") print("done")
8. A Mini Program — Everything Together
# A simple unit converter — celsius to fahrenheit # (Simulating input — replace "100" with input("...") in your own program) celsius_text = "100" try: celsius = float(celsius_text) fahrenheit = (celsius * 9 / 5) + 32 print(f"{celsius}°C = {fahrenheit}°F") except ValueError: print(f"'{celsius_text}' is not a valid temperature.")
That's a working program. Take it, change celsius_text, click Run. Try a non-number value and watch the except branch fire.
🎯 Your Turn — Print a Receipt That Lines Up
Ragged output is the first thing that makes a program look amateur. Writeprint_receipt(items) where items is a list of (name, quantity, unit_price)
tuples, and print a receipt whose columns line up no matter how long the names
are.
Names left-aligned in 14 characters, quantity right-aligned in 3, line total
right-aligned in 9 with two decimals.
Tea 2 90.00 Filter Coffee 1 120.00 Masala Dosa 3 240.00 ------------------------------ TOTAL 450.00
Skeleton:
def print_receipt(items): total = 0 for name, qty, price in items: line_total = qty * price # TODO 1: accumulate into total # TODO 2: print name, qty and line_total using f-string alignment ... # TODO 3: print the rule and the TOTAL row, aligned with the column above ... print_receipt([("Tea", 2, 45.0), ("Filter Coffee", 1, 120.0), ("Masala Dosa", 3, 80.0)])
Hint 1 — Alignment lives inside the f-string
After the colon in an f-string placeholder you can give an alignment and a width:{name:<14} pads on the right to 14 characters,
{qty:>3} pads on the left to 3. Combine with a format spec for
decimals: {amount:>9.2f}.
Hint 2 — The TOTAL row must match the columns above it
The amount column starts after 14 + 3 characters of earlier columns. Pad the wordTOTAL to that same width so the numbers stack:
f"{'TOTAL':<17}{total:>9.2f}".
Show full solution
def print_receipt(items): total = 0 for name, qty, price in items: line_total = qty * price total += line_total print(f"{name:<14}{qty:>3}{line_total:>9.2f}") print("-" * 30) print(f"{'TOTAL':<17}{total:>9.2f}") print_receipt([ ("Tea", 2, 45.0), ("Filter Coffee", 1, 120.0), ("Masala Dosa", 3, 80.0), ])
Three format specs do all the work. :<14 left-aligns and pads names to a fixed
width, :>3 and :>9.2f right-align the numbers so the decimal points stack in
a straight line. Right-alignment is what makes a column of money readable — the
digits line up by place value, so you can compare magnitudes at a glance.
Recap
print()sends output to the screen. Usesep,end,fileto control formatting.input()waits for the user to type and press Enter. Returns a string, always.- Convert immediately with
int(),float(),str(), orbool()afterinput(). int()only parses whole numbers — useint(float(x))for decimals.- Wrap in
try/except ValueErrorwhen you want to handle bad input gracefully.
You now have everything you need to build interactive Python programs. The next lesson covers operators — the things you do with the values you've just collected.
Source: adapted from Python official documentation Section 7 (Input and Output). PSF License.
Practice this
on practicepython.inShort exercises that run in your browser and tell you what your code actually did, not just whether a test passed.