Syntax and Core Concepts

Chapter Outline

Chapter 2: Python Syntax and Core Concepts

Now that your development environment is ready, it’s time to get hands-on with Python syntax and core programming concepts. In this chapter, we’ll cover:

  • Variables and Data Types
  • Operators
  • Conditional Statements
  • Loops
  • Functions and Modules
  • A practical project: Building a simple CLI-based calculator
  • Writing unit tests for your calculator

2.1 Variables and Data Types

Python Data Types

CategoryData TypeDescriptionExample
NumericintInteger numbersx = 5
floatFloating-point (decimal) numbersy = 3.14
complexComplex numbers (real + imaginary)z = 2 + 3j
SequencestrText/string dataname = "Python"
listOrdered, mutable collectionfruits = ["apple", "banana"]
tupleOrdered, immutable collectioncoords = (10.0, 20.0)
rangeSequence of numbers (used in loops)r = range(5)
MappingdictKey-value pairsperson = {"name": "Alice", "age": 25}
SetsetUnordered, unique elementscolors = {"red", "green"}
frozensetImmutable setf_colors = frozenset(["red", "green"])
BooleanboolBoolean value (True or False)is_active = True
BinarybytesImmutable byte sequencedata = b'hello'
bytearrayMutable byte sequenceba = bytearray([65, 66])
memoryviewMemory-efficient view of binary datamv = memoryview(ba)
None TypeNoneTypeRepresents absence of valueresult = None
User-definedCustom ClassClasses defined by developersclass Dog: pass
d = Dog()

Python Variables

In Python, a variable is a name that refers to a value stored in memory. Variables allow you to store, retrieve, and manipulate data in your programs.

Key Features of Python Variables

FeatureExplanation
Dynamically TypedYou don’t need to declare the variable type explicitly. Python infers it automatically.
No Explicit DeclarationSimply assign a value to create a variable.
Reassignment AllowedYou can change the value and even the type of data a variable holds later in your code.
Case Sensitivename and Name are treated as two different variables.

Example Variable Declarations

python
# Integer variable
age = 25
# String variable
name = "Alice"
# Float variable
price = 19.99
# Boolean variable
is_active = True

Variable Naming Rules

  1. Variable names can contain letters, numbers, and underscores.
  2. They cannot start with a number.
  3. No spaces allowed.
  4. Reserved keywords like class, if, return, etc., cannot be used as variable names.

✅ Valid examples:

python
user_name = "Bob"
userAge = 30
_user_location = "NY"

❌ Invalid examples:

python
2user = "Error" # Starts with a number
user-name = "Error" # Contains a hyphen
class = "Error" # Reserved keyword

Dynamic Typing Example

python
x = 10 # x is an integer
x = "Hello" # x is now a string
x = 3.14 # x is now a float

Python doesn’t require you to declare the type beforehand.

Multiple Variable Assignment

python
a, b, c = 1, 2, 3
# Or assign the same value to multiple variables
x = y = z = 0

Swapping Variables

Python makes it easy to swap values without a temporary variable:

python
x, y = 5, 10
x, y = y, x
print(x, y) # Output: 10 5

Type Checking:

You can check the type of a variable using:

python
name = "Alice"
print(type(name)) # Output: <class 'str'>

Notes:

2.2 Operators

Like all high level programming languages, Python comes with many operators of various kinds, to work with data of different types.

Categories of Python Operators

CategoryDescription
Arithmetic OperatorsPerform mathematical calculations
Assignment OperatorsAssign values to variables
Comparison OperatorsCompare two values
Logical OperatorsCombine conditional statements
Identity OperatorsCompare object identity (is)
Membership OperatorsCheck existence in sequences (in)
Bitwise OperatorsOperate at the binary level

Arithmetic Operators

OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 22.5
//Floor Division5 // 22
%Modulus (remainder)5 % 21
**Exponentiation2 ** 38

Assignment Operators

Used to assign and modify values.

OperatorExampleEquivalent to
=a = 5
+=a += 1a = a + 1
-=a -= 2a = a - 2
*=a *= 3a = a * 3
/=a /= 4a = a / 4
//=a //= 2a = a // 2
%=a %= 3a = a % 3
**=a **= 2a = a ** 2

Comparison (Relational) Operators

Return Boolean values.

OperatorDescriptionExampleResult
==Equal3 == 3True
!=Not equal4 != 5True
>Greater than5 > 2True
<Less than3 < 1False
>=Greater than or equal5 >= 5True
<=Less than or equal4 <= 5True

Logical Operators

Used to combine multiple conditions.

OperatorDescriptionExampleResult
andTrue if bothx > 1 and x < 10True/False
orTrue if eitherx < 0 or x > 5True/False
notNegates conditionnot (x == 3)True/False

Identity Operators

Used to compare memory addresses, not values.

python
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True
print(a is c) # False
print(a == c) # True (values are equal)
OperatorDescription
isTrue if same object
is notTrue if not same obj

Membership Operators

Check whether a value is in a container.

python
my_list = [1, 2, 3]
print(2 in my_list) # True
print(4 not in my_list) # True
OperatorDescription
inTrue if found in object
not inTrue if not found

Bitwise Operators

Operate at the bit level.

OperatorSymbolUse Case
AND&a & b
OR|a | b
XOR^a ^ b
NOT~~a
Left Shift<<a << 2
Right Shift>>a >> 2

Operator Precedence

Precedence determines order of execution in expressions.

Precedence LevelOperators
Highest() (Parentheses)
** (Exponentiation)
+, - (Unary)
*, /, //, %
+, -
Comparison: ==, !=, <, >
Logical: not, and, or
Lowest= (Assignment)

2.3 Conditional Statements

if/elif/else statements

Python uses indentation (not curly braces) for blocks of code.

python
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x equals 5")
else:
print("x is less than 5")

match/case statements

Python's match statement, introduced in Python 3.10, provides structural pattern matching, offering a more concise and readable alternative to multiple if/elif/else statements for certain scenarios.

Here are examples illustrating various uses of the match statement:

  1. Simple Value Matching:
python
status_code = 200
match status_code:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Internal Server Error")
case _: # Default case, matches anything not previously matched
print("Unknown Status")
  1. Matching Multiple Values with | (OR operator):
python
day = "Saturday"
match day:
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
print("It's a weekday.")
case "Saturday" | "Sunday":
print("It's the weekend!")
case _:
print("Invalid day.")
  1. Matching with Guards (Conditional Cases):
python
score = 85
subject = "Math"
match subject:
case "Math" if score >= 90:
print("Excellent in Math!")
case "Math" if score >= 70:
print("Good in Math.")
case "Science" if score >= 80:
print("Great in Science!")
case _:
print("Needs improvement or unknown subject.")
  1. Matching Sequences (Lists and Tuples):

Here we're using structural pattern matching, introduced in Python 3.10.

python
command = ["move", "north"]
match command:
case ["move", direction]:
print(f"Moving in direction: {direction}")
case ["attack", target, weapon]:
print(f"Attacking {target} with {weapon}")
case _:
print("Unknown command.")
  1. Matching Objects (Class Instances):
python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(5, 0)
match p:
case Point(x=0, y=0):
print("Origin")
case Point(x=x_val, y=0):
print(f"On X-axis at x={x_val}")
case Point(x=0, y=y_val):
print(f"On Y-axis at y={y_val}")
case Point(x=x_val, y=y_val):
print(f"Point at ({x_val}, {y_val})")
  1. Capturing Sub-patterns and Wildcards:
python
data = ("error", 401, "Unauthorized")
match data:
case ("success", value):
print(f"Operation successful with value: {value}")
case ("error", code, message):
print(f"Error {code}: {message}")
case _:
print("Unrecognized data format.")

2.4 Loops

For Loop

python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

While Loop:

python
count = 0
while count < 3:
print(f"Count is {count}")
count += 1

Loop Control Statements:

  • break: Exit the loop early
  • continue: Skip to the next iteration

2.5 Functions and Modules

The def keyword is used to define a function in Python. Functions help organize and reuse your code.

python
def add(a, b):
return a + b
result = add(2, 3)
print(result) # Output: 5

You can also import functions from modules (files).

Example: If you had a file math_utils.py:

math_utils.py
1def multiply(a, b):
2 return a * b

You can import and use it like this:

python
from math_utils import multiply
print(multiply(3, 4)) # Output: 12

2.6 Comments

Comments are lines ignored by the Python interpreter. They're used to explain what the code does, document tricky logic, or temporarily disable code.

Single-Line Comments

Use the # symbol to start a single-line comment:

python
# This is a single-line comment
print("Hello, World!") # This prints a greeting

Everything after the # is ignored by Python.

Multi-Line Comments (Convention)

Python does not have a native multi-line comment syntax. Instead, we use multiple # lines:

python
# This script calculates
# the square of a number
# and prints the result

Alternatively, you can use a triple-quoted string that isn’t assigned:

python
"""
This is not a true multi-line comment,
but it behaves like one and is commonly used
for documentation or disabling code temporarily.
"""

However, triple quotes are typically reserved for docstrings (see below).

Docstrings: Comments for Documentation

Python supports inline documentation using docstrings—strings enclosed in triple quotes at the start of a module, function, or class.

python
def greet(name):
"""
This function greets the user by name.
"""
return f"Hello, {name}"

You can access docstrings using:

python
print(greet.__doc__)

This is useful for auto-generating documentation with tools like Sphinx or IDE tooltips.

Example Project: CLI-Based Calculator

Let’s build a simple command-line calculator supporting addition, subtraction, multiplication, and division.

calculator.py
1def add(a, b):
2 return a + b
3
4def subtract(a, b):
5 return a - b
6
7def multiply(a, b):
8 return a * b
9
10def divide(a, b):
11 if b == 0:
12 raise ValueError("Cannot divide by zero")
13 return a / b
14
15def main():
16 print("Simple CLI Calculator")
17 print("Operations: add, subtract, multiply, divide")
18
19 operation = input("Enter operation: ").strip().lower()
20 try:
21 num1 = float(input("Enter first number: "))
22 num2 = float(input("Enter second number: "))
23
24 if operation == "add":
25 result = add(num1, num2)
26 elif operation == "subtract":
27 result = subtract(num1, num2)
28 elif operation == "multiply":
29 result = multiply(num1, num2)
30 elif operation == "divide":
31 result = divide(num1, num2)
32 else:
33 print("Invalid operation")
34 return
35
36 print(f"Result: {result}")
37
38 except ValueError as e:
39 print(f"Error: {e}")
40
41if __name__ == "__main__":
42 main()

Running the Calculator

bash
python calculator.py

Example interaction:

bash
Simple CLI Calculator
Operations: add, subtract, multiply, divide
Enter operation: add
Enter first number: 10
Enter second number: 5
Result: 15.0

Writing Unit Tests for the Calculator

Now, let's create a unit test file.

File: test_calculator.py

test_calculator.py
1import pytest
2from calculator import add, sub, mul, div
3
4def test_addition():
5 assert add(1, 2) == 3
6
7def test_subtraction():
8 assert sub(5, 2) == 3
9
10def test_multiplication():
11 assert mul(2, 3) == 6
12
13def test_division():
14 assert div(6, 2) == 3
15
16def test_division_by_zero():
17 with pytest.raises(ValueError, match="Division by zero"):
18 div(2, 0)

Running Your Tests:

bash
pytest

Expected Output:

bash
collected 5 items
test_calculator.py ..... [83%]
5 passed in 0.03s

The reason why the test coverage isn't 100% is because the main() function in the module wasn't tested. We could achieve 100% test coverage of the business logic by moving the arithmatic functions into a separate module, calculator_operations.py for instance, and writing tests for it.

2.7 How This Ties to Web Development Later

Understanding data types, control structures, and functions lays the groundwork for writing API routes, services, and business logic layers in frameworks like FastAPI and Django.

For example:

  • The main() function above mirrors a simple web controller
  • Validation logic (like checking for divide by zero) will later appear in API request validation

Conclusion

You’ve learned:

  • Python variables and types
  • Conditionals and loops
  • Functions and modules
  • How to write and test a simple calculator app

What is Next?

In Chapter 3: Working with Files and Data Serialization, we’ll cover:

  • Reading and writing files
  • Parsing JSON and CSV
  • Practical example: Log file parser that outputs JSON

Check your understanding

Test your knowledge of Python Syntax and Core Concepts

Feedback