Python print() — From Basics to Pro
Not just for strings: print variables, expressions, and even function results. Learn every useful variation — and the common errors beginners actually make.
Why print() matters
print() is the quickest way to see what your code is doing.
It can display strings, numbers, variables, expressions, and even the return values of functions/methods.
It’s also where beginners hit their first errors — so we’ll learn the right usage and the common mistakes (with real error messages).
1) Quick start
print("Hello, Python!")
Output:
Hello, Python!
2) Strings vs Variables
Strings need quotes; variables do not.
# String literal (quotes)
print("alice")
# Variable (no quotes)
alice = "Alice Wonderland"
print(alice)
Output:
alice
Alice Wonderland
print(alice) is perfectly correct if alice is a variable.
It’s only a mistake when you meant to print the literal text "alice".
3) Common beginner errors (and why they happen)
3.1 Case matters: print ≠ Print
Print("Hello") # wrong: capital P
NameError: name 'Print' is not defined
Why? Python is case-sensitive. Print looks like a variable/function you never defined.
3.2 Parentheses are required (Python 3)
print "Hello" # wrong in Python 3
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?
3.3 Forgot the quotes around text
print(alice) # alice is NOT defined as a variable yet
NameError: name 'alice' is not defined
Fix: use quotes if you mean the word “alice”:
print("alice")
3.4 Mismatched quotes
print("Hello') # opens with " but closes with '
SyntaxError: EOL while scanning string literal
Fix: match your quotes:
print("Hello")
4) Printing multiple values, separators, and endings
print() can take many arguments and auto-spaces them:
print("Name:", "Alice", "Age:", 25) # auto spaces between args
Change the separator with sep=
print("2025", "08", "25", sep="-") # 2025-08-25
print("apple", "banana", "cherry", sep=" | ")
Change the line ending with end=
print("Loading", end="...") # no newline yet
print(" done") # continues on same line
Unpacking iterables
nums = [1, 2, 3]
print(*nums) # 1 2 3 (honors sep= if provided)
print(*nums, sep=", ") # 1, 2, 3
5) Printing variables, expressions, and function/method results
Anything that produces a value can go inside print().
Variables and expressions
x = 7
y = 5
print("Sum:", x + y) # Sum: 12
print("Is x > y?", x > y) # Is x > y? True
Function calls in print()
def area(w, h):
return w * h
print(area(3, 4)) # prints 12 (return value)
Method chains in print()
print(" hello ".strip().upper()) # HELLO
print(sorted([3, 1, 2])) # [1, 2, 3]
print(len("python")) # 6
Beware: printing the result of a function that returns None
def shout(msg):
print(msg.upper()) # side-effect print, but returns None
print(shout("hi")) # prints "HI" then prints "None"
Why “None”? print() always prints the value you give it. shout() didn’t return anything, so it returns None by default.
6) Pretty output with f-strings (and alternatives)
f-strings (recommended)
name = "Alice"
age = 25
pi = 3.14159
print(f"My name is {name} and I am {age}.")
print(f"Pi rounded to 2 decimals: {pi:.2f}")
print(f"Zero-padded: {42:05d}") # 00042
print(f"With commas: {1234567:,}") # 1,234,567
str.format() and % (older styles)
print("My name is {} and I am {}.".format(name, age))
print("Pi is %.2f" % pi)
str() vs repr() (human vs developer view)
s = 'Alice'
print(str(s)) # Alice
print(repr(s)) # 'Alice' (shows quotes)
print([1, 2, 3]) # uses str() on elements
print(repr([1, 2, 3])) # developer-friendly representation
7) Strings, quotes, and escape sequences
print("She said, \"Python is fun!\"")
print('It\'s easy to learn.')
print("Line1\nLine2")
print("Column1\tColumn2")
print(r"C:\Users\Alice\Docs") # raw string, backslashes not treated specially
print("Emoji:", "🐍")
8) Printing lists & dicts nicely
Join strings
fruits = ["apple", "banana", "cherry"]
print(", ".join(fruits)) # apple, banana, cherry
Pretty-print nested data
from pprint import pprint
data = {"user": "alice", "scores": [92, 85, 97]}
pprint(data) # nicely formatted for humans
JSON style
import json
print(json.dumps(data, indent=2))
9) Printing without newlines, progress, and redirecting output
Progress lines
import time
for i in range(3):
print(f"Step {i+1}/3", end="\r", flush=True) # overwrite same line
time.sleep(0.5)
print("Done! ")
Force output immediately
print("Writing now...", flush=True)
Print to files or stderr
import sys
# to a file
with open("output.txt", "w", encoding="utf-8") as f:
print("Saved to file", file=f)
# to error stream
print("Something went wrong!", file=sys.stderr)
10) Do & Don’t (pro tips)
- Do keep
print()lowercase and always use parentheses. - Do use quotes for text; no quotes for variables.
- Do prefer f-strings for readable formatting.
- Do use
sep=,end=, and*-unpacking for neat output. - Don’t use
+to concatenate non-strings (it can error); letprint()convert values for you or use f-strings. - Don’t rely on
print()for serious apps — learnlogginglater.
11) Practice time
- Set
name = "Alex"andscore = 95, then printAlex scored 95/100using an f-string. - Print the list
[1, 2, 3, 4]as1-2-3-4using unpacking andsep="-". - Write and print the result of a function
double(n)that returns2 * n. - Call a function that does not return anything and show that
print()would displayNone. - Pretty-print a dictionary with
pprintand withjson.dumps(..., indent=2)— compare.
Wrap-up
print() is more than a “Hello, World!” tool. You can print variables, expressions, return values, and format output beautifully.
Remember: lowercase p, parentheses required, quotes for text, and use f-strings for clarity.
You can run the codes here and practice:
No comments:
Post a Comment