Skip to main content

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("Hello, World!")
print(42)
print(3.14)
city = "Tokyo"
print(city)
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("Line 1")
print("Line 2")
print("Line 3")
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

MistakeExampleFix
Missing colon after if/forif x > 0Add :if x > 0:
Wrong indentation2 spaces instead of 4Stick to 4 spaces
Missing quotesprint(hello)Write print("hello")
Unclosed parenthesisprint("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

  1. Indent it: Write an if block that prints "Positive!" when a number is greater than 0.
  2. Format: Use an f-string to print your name and age on one line.
  3. Separator: Print the date 2024/06/15 using print("2024", "06", "15", sep="/").
  4. No newline: Print "Loading..." without a newline, then "Done!" on the same line.

What's Next

Lesson 3: Variables, Names, and Casting