Python Tutorial for Beginners #5 - User Input & Output (input(), print(), Mini Project)
Video: Python Tutorial for Beginners #5 - User Input & Output (input(), print(), Mini Project) by Taught by Celeste AI - AI Coding Coach
Python User Input & Output
input("prompt? ")reads a line from the user (always as a string).int(input(...))for numbers.sep=andend=andf"..."for formatted output.
Interactive scripts need to read input and produce output. Python's input() and print() cover both.
input(): reading from the user
name = input("What is your name? ")
print(f"Hello, {name}!")
input(prompt) displays prompt, waits for the user to type a line, returns the line as a string. Newline is stripped.
Run it:
What is your name? Alice
Hello, Alice!
input() always returns a string
age = input("How old are you? ")
# age is a string, even if user types digits
next_age = age + 1 # ERROR — can't add int to str
To do arithmetic, convert:
age = int(input("How old are you? "))
next_age = age + 1
print(f"Next year you will be {next_age}")
int(...) converts the string to int. float(...) for decimals.
If the user types non-numeric input, int(...) raises ValueError. Always handle bad input:
try:
age = int(input("How old? "))
except ValueError:
print("That's not a number!")
We dive into exceptions in lesson 16.
A temperature converter
print("Temperature Converter")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
choice = input("Enter choice (1 or 2): ")
temp = float(input("Enter temperature: "))
if choice == "1":
result = temp * 9/5 + 32
print(f"{temp}°C = {result:.1f}°F")
else:
result = (temp - 32) * 5/9
print(f"{temp}°F = {result:.1f}°C")
Three input calls (technically two — choice and temp), one if/else, formatted output. The whole "interactive program" pattern in 12 lines.
{result:.1f} formats to 1 decimal place — episode 3's f-string syntax.
print(): customizing the output
print("Python", "is", "awesome")
# Python is awesome (default: space-separated)
print(*args) — accepts any number of arguments. Default separator is space; default end is newline.
sep= keyword
print("2025", "01", "15", sep="-")
# 2025-01-15
print("Alice", "Bob", "Charlie", sep=" | ")
# Alice | Bob | Charlie
sep=delimiter controls what goes between args. Useful for CSV-style output, formatted tables.
end= keyword
print("Loading", end="")
print("...", end="")
print(" Done!")
# Loading... Done!
end=text controls what goes after. Default is "\n" (newline). Empty string "" keeps the cursor on the same line. Useful for progress indicators.
For real progress bars, use tqdm — much nicer.
Formatted columns
print(f"{'Name':<10} {'Score':>5}")
print(f"{'Alice':<10} {95:>5}")
print(f"{'Bob':<10} {87:>5}")
print(f"{'Charlie':<10} {92:>5}")
Output:
Name Score
Alice 95
Bob 87
Charlie 92
{value:<10} left-aligns, width 10. {value:>10} right-aligns. {value:^10} centers.
For a :-format spec on a string: < left, > right, ^ center, then width.
For numbers, you can combine alignment with formatting:
print(f"{3.14159:>10.2f}") # ' 3.14' — width 10, 2 decimals, right-aligned
Multiple inputs in one line
parts = input("Enter name and age (comma-separated): ").split(",")
name = parts[0].strip()
age = int(parts[1].strip())
print(f"{name} is {age}")
Or with tuple unpacking:
name, age = input().split(",")
name = name.strip()
age = int(age.strip())
For separated values, split + strip + convert is the pattern.
Reading until EOF
import sys
for line in sys.stdin:
print(line.strip())
Reads from stdin until EOF (Ctrl-D on Linux/Mac, Ctrl-Z on Windows). Handles piped input:
cat names.txt | python script.py
For interactive use, input() per call is cleaner.
Validating input
def get_int(prompt, min_val=None, max_val=None):
while True:
raw = input(prompt)
try:
n = int(raw)
except ValueError:
print("Not a number. Try again.")
continue
if min_val is not None and n < min_val:
print(f"Must be >= {min_val}")
continue
if max_val is not None and n > max_val:
print(f"Must be <= {max_val}")
continue
return n
age = get_int("Age: ", min_val=0, max_val=120)
Loop until valid. Helper functions like this are useful for any interactive script.
getpass for hidden input
from getpass import getpass
password = getpass("Password: ") # not echoed to terminal
For passwords or sensitive input. Same as input() but the typed characters don't appear.
Standard streams
import sys
print("hello", file=sys.stdout) # default
print("error", file=sys.stderr) # to stderr
stdout and stderr are separate streams. Errors should go to stderr (so users can pipe stdout to a file without losing them).
For command-line tools:
./script.py 2>errors.log >output.txt
2> redirects stderr; > redirects stdout.
Common stumbles
Forgetting int() for arithmetic. input() returns str; int(input()) for numbers.
input without prompt. Works, but the user doesn't know what to type. Always supply a prompt.
Crashing on bad input. Wrap int(input()) in try/except.
Forgetting f prefix. "value: {x}" is just text. f"value: {x}" interpolates.
Mixing print formats. Pick f-strings; the older % and .format() styles still work but are noisier.
Hardcoded \n. print("line\n") produces two newlines (the \n in the string + print's default). Either use print("line") (auto newline) or print("line", end="").
What's next
Lesson 6: conditionals. if, elif, else, plus and, or, not. Branching logic.
Recap
input(prompt) reads a line as a string. Convert with int() or float() for numbers — wrap in try/except for bad input. print() accepts multiple args; sep= controls separator, end= controls trailing output (default newline). Format with f-strings: alignment (< > ^), width, decimals ({x:.2f}). For passwords, getpass. Standard streams sys.stdout, sys.stderr for redirection.
Next lesson: conditionals.