Syntax, Statements, and Output
What You'll Learn
How Python reads code line by line, why indentation matters, and how to use print() to display results.
Python Is Indentation-Sensitive
Most languages use {} braces to group code. Python uses indentation (spaces/tabs) instead.
This is correct:
if True:
print("Inside the if block")
print("Outside the if block")
This will cause an error:
if True:
print("Missing indentation!") # IndentationError
Rule: Use 4 spaces per indentation level. Never mix spaces and tabs.
Statements
A statement is one instruction for Python to execute. Each line is usually one statement:
name = "Alice" # statement 1: assign a value
age = 30 # statement 2: assign another value
print(name, age) # statement 3: display them
You can split a long statement across lines using \:
total = 100 + 200 + \
300 + 400
print(total) # 1000
The print() Function
print() displays text or values in the terminal. It's the most important tool for learning Python.
Print a string
print("Hello, World!")
Print a number
print(42)
print(3.14)
Print a variable
city = "Tokyo"
print(city)
Print multiple values
print("Name:", "Alice", "Age:", 30)
# Output: Name: Alice Age: 30
Custom separator
print("2024", "01", "15", sep="-")
# Output: 2024-01-15
Custom ending (default is newline)
print("Loading", end="...")
print("Done")
# Output: Loading...Done
Print on multiple lines
print("Line 1")
print("Line 2")
print("Line 3")
Print a blank line
print()
F-Strings (Formatted Output)
The cleanest way to embed variables in text:
name = "Bob"
score = 95
print(f"Player {name} scored {score} points!")
# Output: Player Bob scored 95 points!
You can put any expression inside {}:
width = 10
height = 5
print(f"Area: {width * height}")
# Output: Area: 50
Indentation in Practice
temperature = 35
if temperature > 30:
print("It's hot!")
print("Drink water.")
else:
print("It's comfortable.")
print("End of weather check.")
Output:
It's hot!
Drink water.
End of weather check.
Common Mistakes
| Mistake | Example | Fix |
|---|---|---|
Missing colon after if/for | if x > 0 | Add : → if x > 0: |
| Wrong indentation | 2 spaces instead of 4 | Stick to 4 spaces |
| Missing quotes | print(hello) | Write print("hello") |
| Unclosed parenthesis | print("hi" | Add closing ) |
Quick Reference
# Basic print
print("text")
print(42)
print(variable)
# Multiple values
print("a", "b", "c") # a b c
print("a", "b", sep="-") # a-b
# No newline at end
print("hello", end=" ")
# F-string
name = "Alice"
print(f"Hi {name}") # Hi Alice
# Blank line
print()
Practice Exercises
- Indent it: Write an
ifblock that prints "Positive!" when a number is greater than 0. - Format: Use an f-string to print your name and age on one line.
- Separator: Print the date
2024/06/15usingprint("2024", "06", "15", sep="/"). - No newline: Print
"Loading..."without a newline, then"Done!"on the same line.