Introduction
In this lesson you will learn how to say things to Python (statements), how to ask it to compute something (expressions), and how to talk to humans reading your code (comments). You’ll practice writing and evaluating expressions, constructing different statement types, documenting your code, and spotting common syntax mistakes.
1. Expressions vs. Statements
What is an Expression?
An expression is anything that Python can evaluate to a single value.
Examples of expressions:
3 + 4 # arithmetic expression
name.lower() # method call expression
price * quantity # expression using variables
len("Python") # function call expression
x = 10
x + 5 # expression using a variable
In the interactive shell, expressions show their result. In a script, an expression by itself does nothing unless its result is used (stored, printed, etc.).
What is a Statement?
A statement is a complete instruction that Python can execute. Many statements contain expressions.
Common statements:
- Assignment:
x = 5 - Conditional:
if x > 0: ... - Loop:
for item in items: ... - Function definition:
def greet(): ... - Import:
import math
Example mixing both:
x = 5 + 3 # whole line is a statement
# "5 + 3" is an expression inside the statement
2. Writing and Evaluating Expressions
Expressions with Variables and Operators
price = 19.99
quantity = 3
total = price * quantity + 5 # 5 is, for example, a shipping fee
print(total)
# Output:
64.97
Explanation:
price * quantity + 5is an expression.total = price * quantity + 5is an assignment statement that uses that expression.print(total)is a function call statement that evaluatestotaland outputs it.
Expressions with Function Calls
message = "Python is fun!"
length = len(message) # expression: len(message)
print("Message length:", length)
print("Uppercase:", message.upper())
# Output:
Message length: 14
Uppercase: PYTHON IS FUN!
Explanation:
len(message)andmessage.upper()are expressions that call functions/methods.- Each evaluates to a value used by assignment or
printstatements.
3. Writing Effective Comments
Comments help humans understand why code exists and what it does.
3.1 Single-Line Comments
Use # for single-line comments.
# Calculate final bill including tax and tip
subtotal = 50
tax_rate = 0.1 # 10% tax
tip_rate = 0.15 # 15% tip
final_total = subtotal * (1 + tax_rate + tip_rate)
print("Final total:", final_total)
# Output:
Final total: 62.5
Guidelines:
- Use single-line comments to explain non-obvious logic.
- Avoid restating obvious code like
x = 5 # set x to 5.
3.2 Multi-Line Comments / Docstrings
Python doesn’t have a special multi-line comment syntax, but you can:
- Use multiple
#lines, or - Use triple-quoted strings as docstrings for modules, functions, and classes.
def describe_temperature(celsius):
"""Return a human-friendly description for a temperature.
This helper function converts a numeric Celsius value into a
descriptive string like "cold", "warm", or "hot".
"""
if celsius < 10:
return "cold"
elif celsius < 25:
return "warm"
else:
return "hot"
print(describe_temperature(18))
# Output:
warm
Note: Triple-quoted strings used as the first statement inside a function become that function’s docstring, which tools can display (e.g., help(describe_temperature)).
For general multi-line comments outside functions, prefer repeated #:
# Load data from file
# Validate contents
# Then compute summary statistics
4. Common Syntax Errors and How to Avoid Them
4.1 Mixing Expressions and Statements Incorrectly
# ❌ Invalid: two expressions side by side
1 + 2 3 + 4
Fix by separating statements with new lines or semicolons (new lines are preferred):
# ✅ Valid
print(1 + 2)
print(3 + 4)
4.2 Unterminated or Misplaced Comments
# ❌ Invalid: comment interrupting code in the middle of an expression
result = 10 + # add base value
5
Correct usage:
# ✅ Valid: comment at end of line or on its own line
result = 10 + 5 # add base value
4.3 Using # Inside Strings by Mistake
text = "This is not a comment # it's part of the string"
print(text)
# Output:
This is not a comment # it's part of the string
Reminder: # only starts a comment outside of string literals.
4.4 Missing Colons in Compound Statements
# ❌ SyntaxError: missing colon
if score > 50
print("Passed")
Correct form:
# ✅ Valid
if score > 50:
print("Passed")
4.5 Writing Expressions That Don’t Do Anything
In scripts, an expression alone is pointless unless its result is used:
3 + 4 # does nothing in a script
result = 3 + 4
print(result) # now the result is visible
Summary / Key Takeaways
In this lesson on Statements, Expressions, and Comments, you have learned:
- Expressions vs. statements: An expression produces a value; a statement is a complete instruction that Python executes, often containing one or more expressions.
- Building expressions: You can form valid expressions using literals, variables, operators, function calls, and method calls to compute values.
- Core statement types: Python programs are built from assignment, conditional, loop, and function definition statements that control program flow and structure.
- Role of expressions inside statements: Conditions, arithmetic calculations, and function arguments are all expressions embedded within larger statements.
- Single-line comments: Use
#comments to clarify non-obvious logic and intent without restating what is already obvious from the code. - Docstrings and multi-line documentation: Triple-quoted strings at the start of functions (and modules/classes) serve as docstrings for structured, tool-friendly documentation.
- Common syntax pitfalls: Avoid missing colons, stray expressions that do nothing, malformed comments in the middle of expressions, and misunderstood
#inside strings. - Good habits: Always ensure your code both runs correctly (statements and expressions) and communicates clearly to humans (well-placed, meaningful comments).
