Session 2 - Class Notes
Syntax & Semantics: Indentation · Comments · Variables · Naming Conventions · print()
Topic What You'll Learn
Indentation Python uses spaces/tabs to define code structure
Comments How to write notes in your code (#, triple quotes)
Variables Storing data: numbers, text, True/False
Naming Conventions snake_case, CamelCase, rules for valid names
print() Displaying output: sep, end, f-strings, and more
1. Syntax vs Semantics
Before diving in, let's clarify two key terms you'll hear constantly:
Term Meaning Python Example
Syntax The grammar rules - how code must if x > 0: (colon required)
be written
Semantics What the code actually means / x = 5 means store 5 in x
does at runtime
Key Insight
Syntax errors stop your program before it even runs. Semantic errors let your program run, but it produces
wrong results. Syntax is caught by Python; semantics is caught by you (through testing).
2. Indentation
Python uses indentation (spaces or tabs) to define code blocks - unlike languages that use { } braces.
This is mandatory, not optional.
2.1 The Golden Rules
• Use 4 spaces per indentation level (PEP 8 standard - recommended)
• Never mix spaces and tabs in the same file
• All lines in the same block must be indented identically
• Indentation follows a colon (:) - after if, for, while, def, class
2.2 Code Example
# Correct indentation
age = 20
Session 2 Notes Page 1 of 10
if age >= 18:
print('You are an adult') # 4 spaces
print('You can vote') # same level = same block
else:
print('You are a minor') # 4 spaces inside else
print('This runs always') # back to no indent = outside if/else
Common Mistake
If you get 'IndentationError: expected an indented block' or 'IndentationError: unexpected indent', check your
spacing. Most editors highlight this. VS Code shows a vertical line for each indent level.
3. Comments
Comments are notes written in code for humans to read. Python ignores them completely. They don't
affect how the program runs.
3.1 Single-Line Comments (#)
Use # to start a comment. Everything after # on that line is ignored by Python.
# This is a full-line comment
name = 'Alice' # This is an inline comment
# You can use comments to temporarily disable code:
# print('This line will NOT run')
print('This line WILL run')
3.2 Multi-Line Comments (Triple Quotes)
Python has no built-in multi-line comment syntax. Developers use triple-quoted strings (""" or ''') that are
not assigned to a variable. These are technically string literals, but Python ignores them.
"""
This is a multi-line comment.
It can span as many lines as needed.
Often used at the top of a file or function.
"""
# OR with single quotes:
'''
Another way to write
a multi-line comment.
'''
3.3 Docstrings
Session 2 Notes Page 2 of 10
Docstrings are triple-quoted strings placed right after a def or class statement. They document what the
function does and can be accessed with help().
def greet(name):
"""This function greets a person by name."""
print('Hello, ' + name)
# Access the docstring:
help(greet) # shows the docstring
- Best Practice
Write comments that explain WHY your code does something, not WHAT it does.
Example: # divide by 1000 to convert ms to seconds (good)
Example: # x = x / 1000 (bad - just repeats the code)
4. Variables
A variable is a labelled box that stores a value in memory. You create a variable by assigning it a value
using the = operator.
4.1 Creating Variables
# Syntax: variable_name = value
age = 25 # integer
height = 5.9 # float
name = 'Alice' # string
is_student = True # boolean
# Print them
print(age) # 25
print(name) # Alice
print(is_student) # True
4.2 Python Data Types (the big 4 for beginners)
Type Example Used For
int age = 25 Whole numbers (no decimal)
float price = 9.99 Numbers with decimal points
str name = 'Alice' Text - always in quotes
bool is_on = True True or False values only
4.3 Dynamic Typing
Python is dynamically typed - you don't need to declare the type. Python figures it out automatically.
You can even reassign a variable to a different type.
Session 2 Notes Page 3 of 10
x = 10 # x is an int
print(type(x)) # <class 'int'>
x = 'hello' # now x is a str (valid in Python)
print(type(x)) # <class 'str'>
x = 3.14 # now x is a float
print(type(x)) # <class 'float'>
4.4 Multiple Assignment
# Assign multiple variables in one line
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# Assign the same value to multiple variables
x = y = z = 0
print(x, y, z) # 0 0 0
# Swap two variables (Python magic!)
a, b = b, a
print(a, b) # 2 1
5. Naming Conventions
Good naming makes code readable. Python has strict rules (what's allowed) and community
conventions (what's recommended).
5.1 Naming Rules (enforced by Python)
• Must start with a letter (a–z, A–Z) or underscore (_)
• Can contain letters, digits (0–9), and underscores
• Cannot start with a number
• Cannot be a Python keyword (if, for, while, def, class, etc.)
• Case-sensitive: name, Name, and NAME are three different variables
5.2 Valid vs Invalid Names
Valid Invalid Why Invalid
student_name 1student Starts with a number
_private student-name Hyphens not allowed (that's minus!)
firstName class class is a Python keyword
total_score_2024 my variable Spaces not allowed
Session 2 Notes Page 4 of 10
5.3 Naming Styles (Python Community Standards)
Style Example Use For
snake_case student_name, Variables and functions (most common in
total_score Python)
UPPER_SNAKE_CASE MAX_SIZE, PI Constants (values that never change)
CamelCase StudentProfile, Class names
(PascalCase) BankAccount
_leading_underscore _helper_value Private/internal variables (convention
only)
PEP 8 - Python's Style Guide
PEP 8 is the official style guide for Python code. It recommends snake_case for variables and functions.
Following it makes your code look professional and easier for other Python developers to read.
5.4 Good vs Bad Names
# Bad naming
x = 'Alice'
y = 25
z = True
# -Good naming
student_name = 'Alice'
student_age = 25
is_enrolled = True
# Avoid single letters except in loops
# -Descriptive names make code self-documenting
6. print() - Displaying Output
print() is the most-used function for beginners. It sends output to the terminal/console.
6.1 Basic Usage
print('Hello, World!') # Hello, World!
print(42) # 42
print(3.14) # 3.14
print(True) # True
# Print multiple values
print('Name:', 'Alice') # Name: Alice
print(1, 2, 3) # 1 2 3 (space-separated by default)
Session 2 Notes Page 5 of 10
6.2 print() Parameters
Parameter Default What it does Example
sep ' ' (space) Separator between values print(1,2,3, sep='-') → 1-
2-3
end '\n' What to print at the end print('Hi', end='!') → Hi!
(newline)
file [Link] Where to print (usually (advanced use)
default)
# sep example - change separator
print('2024', '06', '01', sep='-') # 2024-06-01
print('a', 'b', 'c', sep=', ') # a, b, c
# end example - stay on same line
print('Hello', end=' ')
print('World') # Hello World (same line!)
# Combine sep and end
print(1, 2, 3, sep='|', end='\n---\n') # 1|2|3
# ---
6.3 Printing Variables
name = 'Alice'
age = 25
# Method 1: Concatenation (+ operator)
print('Name: ' + name) # Name: Alice
# Can only concatenate strings! int + str causes error.
# Method 2: Comma-separated (adds a space automatically)
print('Age:', age) # Age: 25
# Method 3: str() conversion
print('Age: ' + str(age)) # Age: 25
6.4 f-Strings (Recommended - Python 3.6+)
f-strings (formatted string literals) are the modern, most readable way to embed variables directly inside
a string. Use the letter f before the opening quote.
name = 'Alice'
age = 25
gpa = 3.856
# Basic f-string
print(f'Hello, {name}!') # Hello, Alice!
print(f'{name} is {age} years old.') # Alice is 25 years old.
# Expressions inside {}
print(f'Next year you will be {age + 1}.') # Next year you will be 26.
Session 2 Notes Page 6 of 10
# Format numbers
print(f'GPA: {gpa:.2f}') # GPA: 3.86 (2 decimal places)
print(f'GPA: {gpa:.1f}') # GPA: 3.9 (1 decimal place)
# Combining multiple variables
subject = 'Python'
print(f'{name} is studying {subject} at age {age}.')
# Alice is studying Python at age 25.
- f-strings are the recommended way to format output in modern Python.
They are faster, easier to read, and less error-prone than concatenation.
Memorise the syntax: f'text {variable} more text'
7. Running Python Files - Terminal Commands
Here's how to run your .py files from the terminal/command prompt on both Windows and
macOS/Linux.
Action Windows (Command Prompt / macOS / Linux (Terminal)
PowerShell)
Open terminal Win + R → type cmd → Enter Cmd + Space → type Terminal →
Enter
Check Python version python --version python3 --version
Run a Python file python [Link] python3 [Link]
Navigate to folder cd C:\Users\YourName\Desktop cd ~/Desktop
List files in folder dir ls
Go up one folder cd .. cd ..
Create a new file type nul > [Link] (then touch [Link]
open in editor)
7.1 Step-by-step: Running your first script
Windows:
# 1. Open Command Prompt
> cd Desktop
> python [Link]
macOS / Linux:
# 1. Open Terminal
$ cd ~/Desktop
$ python3 [Link]
Session 2 Notes Page 7 of 10
8. Practice Exercises
Try these exercises on your own to reinforce today's topics. Answers are at the bottom.
Exercise 1 - Fix the Indentation
# This code has an indentation error. Fix it.
score = 85
if score >= 60:
print('Pass')
else:
print('Fail')
Exercise 2 - Variables & print()
# Create variables for: your name, age, and favourite language
# Then print: 'Hi, I'm [name], I'm [age] years old and I love [language]!'
# Use an f-string.
Exercise 3 - Naming
# Rename these variables using proper Python naming conventions:
StudentName = 'Bob'
STUDENTAGE = 22
1stScore = 95
my score = 88
Exercise 4 - print() Formatting
# Use sep and end to produce exactly this output:
# 2024/06/01
# Done!
year = 2024
month = 6
day = 1
# Your code here...
Session 2 Notes Page 8 of 10
9. Session 2 - Quick Reference Cheatsheet
Concept Example Code
Single-line comment # This is a comment
Multi-line comment """ \n comment text \n """
Create a variable age = 25
Check type print(type(age)) # <class 'int'>
Swap variables a, b = b, a
Basic print print('Hello')
print with sep print(1, 2, 3, sep='-') # 1-2-3
print with end print('Hello', end='! ') # Hello!
f-string print(f'Hi {name}')
f-string format print(f'{gpa:.2f}') # 3.86
Run file (Windows) python [Link]
Run file (macOS) python3 [Link]
10. Exercise Answers
Exercise 1
score = 85
if score >= 60:
print('Pass') # ← Added 4 spaces
else:
print('Fail')
Exercise 2
name = 'Alice'
age = 20
language = 'Python'
print(f"Hi, I'm {name}, I'm {age} years old and I love {language}!")
Exercise 3
student_name = 'Bob' # was StudentName
student_age = 22 # was STUDENTAGE
first_score = 95 # was 1stScore (invalid - started with digit)
my_score = 88 # was my score (invalid - had space)
Exercise 4
year = 2024
Session 2 Notes Page 9 of 10
month = 6
day = 1
print(year, month, day, sep='/')
print('Done!')
# Output:
# 2024/6/1
# Done!
Session 2 Notes Page 10 of 10