3.1 Python Syntax
Python syntax means the basic rules used to write valid Python code. These rules control how names, quotation marks, parentheses, colons, operators, and instructions are arranged. Python is designed to be readable, but every symbol still matters. A missing quotation mark, parenthesis, or colon can stop the program and produce an error.
Example: Write simple Python syntax
# Display a greeting
print("Hello, Python!")
# Add two numbers
print(5 + 3)
Explanation: The first print() instruction displays text because the message is inside quotation marks. The second print() instruction calculates 5 + 3 before displaying the answer. Python reads the instructions from top to bottom and follows its syntax rules.
3.2 Python Indentation
Indentation means the spaces placed at the beginning of a line. In Python, indentation is part of the language and not only decoration. It tells Python which instructions belong inside an if statement, loop, function, or another code block. Beginners should normally use four spaces for each indentation level and avoid mixing tabs with spaces.
Example: Use correct indentation
age = 18
if age >= 18:
print("You are an adult.")
print("Access allowed.")
print("Program finished.")
Output:You are an adult.
Access allowed.
Program finished.
Explanation: The two indented print() lines belong to the if statement and run because age is 18. The final line is not indented, so it is outside the if block and runs after the condition is checked.
3.3 Statements
A statement is a complete instruction that tells Python to perform an action. Assigning a value, displaying information, importing a module, and checking a condition are examples of statements. Python normally executes statements from the first line to the last line. Understanding statements helps beginners divide a program into small and understandable actions.
Example: Run statements in order
name = "Sara"
age = 12
print(name)
print(age)
Explanation: The first two statements store values in variables. The next two statements display those values. Python runs each statement in order, beginning with the first line and continuing until the program ends.
3.4 Expressions
An expression is a combination of values, variables, operators, or function calls that produces a result. Expressions can calculate numbers, join text, compare values, or create new values. Python evaluates an expression before using its answer. Expressions are often placed inside print() or on the right side of an assignment statement.
Example: Calculate an expression
price = 10
quantity = 3
total = price * quantity
print(total)
Explanation: The expression price * quantity multiplies 10 by 3. Python evaluates the expression first, stores the answer in total, and then print() displays 30.
3.5 Code Blocks
A code block is a group of related instructions that belong together. Python uses indentation to show where a block begins and ends. Code blocks appear inside conditions, loops, functions, classes, and error-handling structures. Every instruction with the same indentation level belongs to the same block, making the program structure easier to understand.
Example: Create a code block
temperature = 25
if temperature > 20:
print("It is warm.")
print("Wear light clothing.")
print("Weather check complete.")
Output:It is warm.
Wear light clothing.
Weather check complete.
Explanation: The two indented lines form one code block under the if statement. They run because the temperature is greater than 20. The final instruction is outside the block.
3.6 Keywords
Keywords are reserved words that have special meanings in Python. Examples include if, else, for, while, def, class, True, False, and None. A keyword cannot be used as a variable name because Python already uses it as part of the language. Learning common keywords helps beginners recognize the structure of Python programs.
Example: Use Python keywords
score = 75
if score >= 50:
result = True
else:
result = False
print(result)
Explanation: The keywords if and else control a decision. True and False are Boolean keywords. Because the score is 75, the first block runs and result becomes True.
3.7 Identifiers
An identifier is a name created by a programmer for a variable, function, class, or another object. Good identifiers explain the purpose of the value they represent. Names such as student_name and total_price are clearer than short names such as x. Meaningful identifiers make programs easier to read, test, and maintain.
Example: Create meaningful identifiers
student_name = "Omar"
student_score = 92
print(student_name)
print(student_score)
Explanation: student_name and student_score are identifiers. Each name refers to a stored value. The print() function uses those identifiers to find and display the correct values.
3.8 Naming Rules
Python names may contain letters, numbers, and underscores, but they cannot begin with a number. Spaces, hyphens, and many special symbols are not allowed. A name also cannot be a Python keyword. Following these rules prevents syntax errors and helps Python correctly recognize variables, functions, classes, and other identifiers.
Example: Use valid variable names
user_name = "Mina"
score2 = 88
_private_note = "Practice more"
print(user_name)
print(score2)
print(_private_note)
Output:Mina
88
Practice more
Explanation: All three names are valid. user_name uses an underscore, score2 contains a number but does not begin with it, and _private_note begins with an allowed underscore.
3.9 Python Naming Conventions
Naming conventions are recommended styles that make Python code consistent and easy to read. Variables and functions normally use snake_case, classes use PascalCase, and constants use uppercase letters. These styles are not always required by Python, but following them helps other programmers quickly understand the purpose of each name.
Example: Follow naming conventions
student_name = "Lina"
MAX_SCORE = 100
class StudentRecord:
pass
print(student_name)
print(MAX_SCORE)
Explanation: student_name uses snake_case, MAX_SCORE uses uppercase letters for a constant, and StudentRecord uses PascalCase for a class name. The print() calls display the two stored values.
3.10 Comments
Comments are notes written for people who read the code. Python ignores comments when the program runs. Comments can explain a difficult instruction, describe why a decision was made, or remind a programmer about future work. Good comments add useful information instead of repeating something that is already obvious from the code.
Example: Add useful comments
# Store the price before tax
price = 20
# Calculate thirteen percent tax
tax = price * 0.13
# Display the final amount
print(price + tax)
Explanation: The comment lines do not produce output because Python ignores them. The executable lines store the price, calculate the tax, and display the final amount.
3.11 Single-Line Comments
A single-line comment begins with the hash symbol. Everything after the hash on that line is ignored by Python. A comment may appear on its own line or after an instruction. Beginners should keep comments short, accurate, and useful because too many unnecessary comments can make simple code harder to read.
Example: Write a single-line comment
# This is a full-line comment
name = "Ali" # This is an inline comment
print(name)
Explanation: Python skips the full-line comment and ignores the inline comment after the assignment. It still stores Ali in name and displays it with print().
3.12 Multiline Comments
Python does not have a special multiline comment symbol. Programmers usually place a hash symbol at the beginning of each comment line. Triple-quoted strings are sometimes used as long notes, but they are actually string values. For ordinary explanations, several hash-prefixed lines are the clearest and safest beginner method.
Example: Write multiline comments
# This program stores a city.
# It creates a welcome message.
# It then displays the message.
city = "Toronto"
message = "Welcome to " + city
print(message)
Output:Welcome to Toronto
Explanation: The first three lines form a multiline explanation using separate comments. Python ignores them, joins the city name to the message, and displays the completed sentence.
3.13 Docstrings
A docstring is a string placed at the beginning of a function, class, or module to describe its purpose. Docstrings normally use triple quotation marks and may continue across several lines. Unlike ordinary comments, Python tools such as help() can read docstrings. They are useful for explaining how reusable code should be used.
Example: Add a function docstring
def greet(name):
"""Return a friendly greeting."""
return "Hello, " + name
print(greet("Noah"))
print(greet.__doc__)
Output:Hello, Noah
Return a friendly greeting.
Explanation: The function returns a greeting for Noah. The special __doc__ attribute retrieves and displays the function's docstring, showing that documentation can be stored with the function.
3.14 Variables
A variable is a name that refers to a value in memory. Variables allow a program to store information and use it later. The stored value can be text, a number, a Boolean, a list, or another object. Meaningful variable names make the purpose of the stored information clear and reduce repeated typing.
Example: Store values in variables
name = "Ava"
age = 14
is_student = True
print(name)
print(age)
print(is_student)
Explanation: Each assignment connects a variable name to a value. The print() calls retrieve and display those values. Python automatically recognizes their basic data types.
3.15 Creating Variables
A variable is created when a value is assigned to a name with the equals sign. Python does not require a separate declaration before the first assignment. The variable name appears on the left, and the value or expression appears on the right. Python evaluates the right side before storing the result.
Example: Create variables
course = "Python Basics"
lessons = 35
completed = False
print(course)
print(lessons)
print(completed)
Output:Python Basics
35
False
Explanation: The three assignment statements create three variables containing different kinds of values. The print() instructions confirm that the variables were created successfully.
3.16 Changing Variable Values
A variable can receive a new value after it has been created. The new assignment makes the variable refer to the new value instead of the old value. This is useful for scores, counters, totals, and changing program states. Always consider the current value at the exact point where the variable is used.
Example: Change variable values
score = 10
print(score)
score = 25
print(score)
score = score + 5
print(score)
Explanation: The first print() shows the original value. The next assignment changes score to 25. The final assignment adds 5 to the current value and stores 30.
3.17 Multiple Assignment
Multiple assignment allows several variables to receive values in one statement. Python matches each value on the right with a variable on the left by position. The number of variables and values should normally match. This feature can make related assignments shorter, but clear formatting is still important for beginners.
Example: Assign several values
name, age, city = "Leo", 15, "Ottawa"
print(name)
print(age)
print(city)
Explanation: Leo is assigned to name, 15 is assigned to age, and Ottawa is assigned to city. Python matches the values and variables from left to right.
3.18 Unpacking Values
Unpacking means taking values from a collection and assigning them to separate variables. The number of variables must usually match the number of values. Unpacking is useful when a list, tuple, or another sequence contains related information. It allows each value to receive a clear and meaningful name.
Example: Unpack a tuple
student = ("Maya", 13, "Grade 8")
name, age, grade = student
print(name)
print(age)
print(grade)
Explanation: The tuple contains three values. Python unpacks them in order into name, age, and grade. Each print() call then displays one unpacked value.
3.19 Constants by Convention
Python does not prevent a variable from changing, so it has no fully protected constant in normal code. Programmers use uppercase names to show that a value should be treated as constant. This is a convention, not an enforced rule. Other programmers should avoid changing such values unless there is a good reason.
Example: Use constants by convention
PI = 3.14159
TAX_RATE = 0.13
price = 100
print(price * TAX_RATE)
print(PI)
Explanation: PI and TAX_RATE are written in uppercase to show that they should remain unchanged. The program uses TAX_RATE to calculate tax and then displays PI.
3.20 Case Sensitivity
Python is case-sensitive, which means uppercase and lowercase letters are treated as different characters. A variable named age is different from Age or AGE. The same rule applies to function names, class names, and keywords. Beginners should type names exactly the same way every time they use them.
Example: Compare case-sensitive names
name = "Ali"
Name = "Sara"
NAME = "Omar"
print(name)
print(Name)
print(NAME)
Explanation: Python treats name, Name, and NAME as three different identifiers. Each variable stores and displays a different value because capitalization changes the name.
3.21 The print() Function
The print() function displays information in the terminal or output area. It can show text, numbers, variable values, and expression results. Text must normally be placed inside quotation marks. Beginners use print() frequently to test code, view results, and understand what values a program is producing at different steps.
Example: Print different values
print("Welcome to Python")
print(25)
print(7 * 4)
Output:Welcome to Python
25
28
Explanation: The first line displays text, the second displays a number, and the third evaluates 7 * 4 before displaying 28. Each print() call begins on a new line.
3.22 Printing Multiple Values
The print() function can display several values in one call when they are separated by commas. Python automatically places a space between the values. This method is useful because strings and numbers can be printed together without manual conversion. The sep and end arguments can also change the separator and ending character.
Example: Print multiple values
name = "Nora"
age = 14
print("Name:", name, "Age:", age)
print("2026", "07", "18", sep="-")
Output:Name: Nora Age: 14
2026-07-18
Explanation: The first print() joins text and variable values with spaces. The second print() uses a hyphen as the separator, creating a date-like format.
3.23 The input() Function
The input() function pauses a program and waits for the user to type something. The text inside input() is called a prompt and tells the user what to enter. After the user presses Enter, Python returns the typed information as a string. Even numbers entered by the user begin as text.
Example: Ask for user input
name = input("Enter your name: ")
print("Hello,", name)
Output:Enter your name: Emma
Hello, Emma
Explanation: The program waits for the user to type a name. The entered text is stored in name, and print() displays a greeting containing that value.
3.24 Getting User Input
Getting user input makes a program interactive because the result can change depending on what the user enters. A program may ask for a name, city, favorite color, or another piece of information. Clear prompts are important because users need to understand what kind of value they should type.
Example: Collect two user answers
name = input("What is your name? ")
city = input("Where do you live? ")
print(name, "lives in", city)
Example Input:Adam
Toronto
Output:Adam lives in Toronto
Explanation: The program collects two separate answers and stores them in variables. The final print() combines those values into one sentence.
3.25 Converting User Input
The input() function always returns text, even when the user types digits. To perform mathematics, the text must usually be converted with int() or float(). int() creates a whole number, while float() creates a decimal number. Conversion should happen before arithmetic operations are performed on the entered value.
Example: Convert input to a number
age_text = input("Enter your age: ")
age = int(age_text)
print("Next year you will be", age + 1)
Output:Next year you will be 15
Explanation: The entered value begins as the string "14". int() converts it to the integer 14, allowing Python to add 1 and display 15.
3.26 Understanding Objects
In Python, almost every value is an object. An object contains data and belongs to a type that defines what operations it supports. Strings, integers, lists, functions, and classes all create or represent objects. Beginners can think of an object as a value with built-in abilities and information about its type.
Example: Check object types
message = "hello"
number = 25
print(type(message))
print(type(number))
print(message.upper())
Output:<class 'str'>
<class 'int'>
HELLO
Explanation: type() shows that message is a string object and number is an integer object. The string object provides the upper() method, which creates uppercase text.
3.27 Understanding References
A variable usually stores a reference to an object rather than containing the object directly. Two variables can refer to the same object. This becomes important with mutable objects such as lists because changing the object through one variable may also appear through another variable. Understanding references helps explain some surprising beginner results.
Example: Share a list reference
first_list = [1, 2, 3]
second_list = first_list
second_list.append(4)
print(first_list)
print(second_list)
Output:[1, 2, 3, 4]
[1, 2, 3, 4]
Explanation: Both variables refer to the same list object. Adding 4 through second_list changes that shared object, so first_list also shows the updated list.
3.28 Dynamic Typing
Python is dynamically typed, which means a variable name is not permanently limited to one data type. A variable can first refer to a number and later refer to text. Python determines the type from the current value at runtime. This is flexible, but changing types carelessly can make code confusing.
Example: Change a variable type
value = 100
print(value)
print(type(value))
value = "one hundred"
print(value)
print(type(value))
Output:100
<class 'int'>
one hundred
<class 'str'>
Explanation: value first refers to an integer object and later refers to a string object. Python allows this because variable names do not have fixed types.
3.29 Strong Typing
Python is strongly typed, which means it usually does not automatically combine incompatible data types. For example, a string and an integer cannot be added directly. The programmer must clearly convert one value to a compatible type. Strong typing helps prevent unclear operations and makes many mistakes easier to detect.
Example: Convert types safely
age = 14
message = "Age: " + str(age)
print(message)
Explanation: str(age) converts the integer 14 into text. The converted value can then be joined safely with the string "Age: ".
3.30 Basic Error Messages
An error message explains why Python could not continue running a program. The message usually includes the error type, the file name, the line number, and a short description. Beginners should read error messages carefully instead of feeling discouraged. They are helpful clues that point toward the location and cause of a problem.
Example: Read a basic error
number = 10
print(number / 0)
Output:ZeroDivisionError: division by zero
Explanation: Python reports ZeroDivisionError because division by zero is not allowed. The error type tells the beginner what kind of problem occurred and helps identify the instruction that must be fixed.
3.31 Reading Tracebacks
A traceback is the detailed report Python displays when an error occurs. It shows the sequence of function calls that led to the problem and usually ends with the most useful line: the error type and message. Beginners should read from the bottom upward, then check the indicated file and line number.
Example: Read a traceback
def divide(a, b):
return a / b
result = divide(10, 0)
print(result)
Output:Traceback (most recent call last):
File "app.py", line 4, in <module>
result = divide(10, 0)
File "app.py", line 2, in divide
return a / b
ZeroDivisionError: division by zero
Explanation: The traceback shows that the program called divide() and failed on the return line. The final line identifies the problem as division by zero.
3.32 Common Syntax Errors
A syntax error happens when code breaks Python's writing rules. Common causes include missing quotation marks, missing parentheses, missing colons, incorrect indentation, and misspelled keywords. Python normally finds syntax errors before running the program. Carefully checking punctuation and comparing the code with a correct example often solves the problem.
Example: Correct a syntax error
# Incorrect
# if age >= 18
# print("Adult")
# Correct
age = 18
if age >= 18:
print("Adult")
Explanation: The correct if statement includes a colon and an indented instruction. After those syntax problems are fixed, Python can understand the code and display Adult.
3.33 Common Beginner Mistakes
Common beginner mistakes include misspelling variable names, forgetting quotation marks, using the wrong capitalization, mixing tabs and spaces, forgetting to convert input, and using a variable before creating it. These mistakes are normal while learning. Testing small sections and reading error messages carefully makes them easier to find and correct.
Example: Avoid a beginner mistake
age_text = input("Enter your age: ")
age = int(age_text)
next_age = age + 1
print("Next year you will be", next_age)
Output:Next year you will be 13
Explanation: The program avoids a common mistake by converting the input string to an integer before adding 1. Clear variable names also reduce spelling and logic errors.
3.34 Chapter Practice Exercises
Practice exercises help beginners remember syntax, indentation, variables, input, output, conversion, and error reading. Complete each exercise without copying the answer first. Then run the code, compare the result, and correct any errors. Small exercises are valuable because they build confidence before a larger project is attempted.
- Create variables for your name, age, and city, then print them.
- Ask the user for two numbers, convert them, and print their total.
- Create an if statement that prints Adult when age is at least 18.
- Use multiple assignment to store three school subjects.
- Create a constant named TAX_RATE and use it in a calculation.
Example: Add two entered numbers
first = int(input("Enter the first number: "))
second = int(input("Enter the second number: "))
print("Total:", first + second)
Explanation: Both input values are converted to integers. Python adds 7 and 5, stores the result temporarily as an expression result, and print() displays 12.
3.35 Chapter Mini Project
This mini project combines variables, input, conversion, expressions, print(), comments, naming conventions, and basic decision-making. The program asks for a student's name and three scores, calculates the average, and displays a simple result. Beginners should type the code themselves, run it several times, and test different scores.
Example: Student Average Calculator
# Ask for the student's name
student_name = input("Enter the student's name: ")
# Get and convert three scores
score_one = float(input("Enter score 1: "))
score_two = float(input("Enter score 2: "))
score_three = float(input("Enter score 3: "))
# Calculate the average
average_score = (score_one + score_two + score_three) / 3
# Display the student's result
print("Student:", student_name)
print("Average:", round(average_score, 2))
if average_score >= 50:
print("Result: Pass")
else:
print("Result: Needs Improvement")
Example Input:Michael
80
70
90
Output:Student: Michael
Average: 80.0
Result: Pass
Explanation: The three scores are converted to decimal numbers and added together. Dividing by 3 produces an average of 80. Because 80 is at least 50, the if block displays Pass.
How to Run: Save the code in a file named chapter3_project.py. Open a terminal in the same folder and run python chapter3_project.py. On some computers, use python3 chapter3_project.py. Enter each requested value and press Enter after every answer.