Module 3 • Introduction to Python
print() is Python's primary way to display output. It can accept multiple values separated by commas and has two important parameters: sep and end.
When you pass multiple values separated by commas, Python automatically inserts a space between them and converts non-string values to strings:
print("Name:", name, "Age:", age)
# Automatic spaces, automatic str() conversion
sep -- changes the separator between values (default: " " space)end -- changes what appears at the end (default: "\n" newline)print("a", "b", "c", sep="-") # a-b-c
print("Hi", end=" "); print("there") # Hi there
input() pauses the program, shows a prompt, and returns whatever the user types as a string. It ALWAYS returns a string, even if the user types a number.
input() to a number before doing math. age = input("Age: ") stores a string, not a number. age + 1 will cause a TypeError. Fix: age = int(input("Age: ")).
# For strings (no conversion needed)
name = input("Your name: ")
# For integers
age = int(input("Your age: "))
# For decimals
price = float(input("Price: "))
f that let you embed Python expressions inside {}. They are the modern, preferred way to format strings in Python.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
You can put any Python expression inside the curly braces:
print(f"{x} + {y} = {x + y}")
print(f"Upper: {name.upper()}")
print(f"Length: {len(name)}")
:.2f -- 2 decimal places: f"{3.14159:.2f}" produces 3.14:, -- comma separators: f"{1000000:,}" produces 1,000,000:,.2f -- commas + decimals: f"{1234.5:,.2f}" produces 1,234.50:.1% -- percentage: f"{0.875:.1%}" produces 87.5%% format specifier multiplies by 100 automatically. So 0.75 becomes 75%, not 0.75%.
< -- left align: f"{'text':<15}"> -- right align: f"{'text':>15}"^ -- center align: f"{'text':^15}"+ to join strings (no automatic spaces) and * to repeat strings. Remember that concatenation only works between strings -- convert numbers with str() first.
The older way to format strings. Know it for reading existing code, but prefer f-strings:
"Hello, {}!".format(name)
"Pi: {:.2f}".format(3.14159)
Q1: What does input() always return?
A: A string (str). Always, even if the user types a number.
Q2: What is the output of print("x", "y", "z", sep="")?
A: xyz -- empty string separator means no space between values.
Q3: What does f"{9.99:.0f}" produce?
A: 10 -- zero decimal places, so 9.99 rounds to 10.
Q4: How do you display the number 0.42 as a percentage with no decimal places?
A: f"{0.42:.0%}" produces 42%
Q5: What is wrong with "Total: " + 99.99?
A: TypeError -- you cannot concatenate a string with a float. Fix: "Total: " + str(99.99) or better yet f"Total: {99.99}"
Q6: What does print("Hi", end="!!! ") followed by print("Bye") output?
A: Hi!!! Bye -- the end parameter replaces the newline with "!!! ".
f+*: in f-strings (:.2f, :,, etc.)