Module 1: Python Foundations – Complete Chapter
Welcome to Module 1 of our Python & MongoDB course. This chapter will build a strong foundation in Python programming.
We’ll cover installation, setup, data types, control structures, functions, exception handling, file operations, and basic object-oriented programming (OOP).
Each topic includes detailed explanations, practical code examples, and beginner-friendly notes.
✅ Python Installation & Setup
Python is a versatile programming language used for web development, data analysis, automation, and more. Before coding, you must install Python and set up a virtual environment.
🔹 Windows Installation
- Download the latest Python installer from python.org.
- Run the installer and check
Add Python to PATHbefore clicking “Install Now”. - Verify installation in Command Prompt:
python --version
pip --version
🔹 Linux Installation
Most Linux distributions come with Python pre-installed. To install or update:
sudo apt update
sudo apt install python3 python3-pip
🔹 macOS Installation
Install via Homebrew:
brew install python
🔹 Virtual Environments
Virtual environments help isolate project dependencies. Create one using:
python -m venv venv
# Activate venv
# Windows
venv\Scripts\activate
# macOS/Linux
source venv/bin/activate
# Deactivate environment
deactivate
Best Practice: Always create a separate virtual environment per project to avoid dependency conflicts.
✅ Python Data Types & Variables
Python is dynamically typed; variable types are inferred. Understanding types is key for writing correct programs.
🔹 Numbers
x = 10 # integer
y = 3.14 # float
z = 2 + 3j # complex number
print(type(x), type(y), type(z))
🔹 Strings
name = "Ali"
greeting = 'Hello, World!'
multiline = """This is
a multiline
string."""
print(name, greeting, multiline)
🔹 Boolean
flag = True
done = False
if flag:
print("Flag is True")
🔹 Type Conversion
a = "100"
b = int(a) # string to int
c = float(b) # int to float
print(a, b, c) # "100" 100 100.0
🔹 Beginner Notes
- Use descriptive variable names for readability.
- Python is case-sensitive:
Age≠age. - Dynamic typing is flexible but can cause runtime errors if types are mismatched.
✅ Lists, Tuples, Sets, and Dictionaries
Python collections allow storing multiple items in one variable.
🔹 Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[0]) # apple
print(fruits[-1]) # orange
🔹 Tuples
coordinates = (10.0, 20.0)
# Tuples are immutable
print(coordinates[0])
🔹 Sets
numbers = {1, 2, 3, 2}
numbers.add(4)
print(numbers) # {1,2,3,4} (duplicates removed)
🔹 Dictionaries
person = {"name": "Ali", "age": 30}
person["email"] = "ali@example.com"
print(person["name"])
🔹 Best Practices & Common Mistakes
- Use lists for ordered collections, sets for unique elements, dicts for key-value mapping.
- Accessing non-existent keys in dicts raises
KeyError; usedict.get()instead.
✅ Control Structures: if, loops
Decision-making and loops allow dynamic behavior in your programs.
🔹 If-Else Statements
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
🔹 For Loops
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
🔹 While Loops
count = 0
while count < 5:
print(count)
count += 1
🔹 Best Practice
- Avoid infinite loops unless intentional.
- Use descriptive loop variables.
✅ Functions, Modules & Imports
Functions are reusable code blocks. Modules group related functions.
def greet(name):
return f"Hello, {name}!"
print(greet("Ali"))
# Using built-in modules
import math
print(math.sqrt(16))
# Import with alias
import datetime as dt
print(dt.datetime.now())
🔹 Best Practices
- Name functions clearly (
snake_case). - Use docstrings to describe function purpose.
✅ Exception Handling
try:
x = int(input("Enter a number: "))
print(10 / x)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")
- Always handle exceptions gracefully.
- Use
finallyfor cleanup code.
✅ File Handling (Text, CSV, JSON)
# Text file
with open("data.txt", "w") as f:
f.write("Hello Python\n")
with open("data.txt", "r") as f:
print(f.read())
# JSON
import json
data = {"name": "Ali", "age": 30}
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json", "r") as f:
content = json.load(f)
print(content)
✅ Basic Object-Oriented Programming (OOP)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}")
# Inheritance
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
s = Student("Ali", 20, "S001")
s.greet()
🔹 Best Practices
- Use meaningful class and method names.
- Follow DRY principle (Don’t Repeat Yourself).
- Encapsulate data using private attributes when needed.
✅ Exercises
- Write a function that takes a list of numbers and returns their sum.
- Create a class
Carwith attributesmake,model,yearand a methoddisplay_info(). - Read a CSV file containing user data and print all emails.
- Handle exceptions for invalid integer input in a program.
Congratulations! You have completed Module 1: Python Foundations. You now have the skills to work with Python data types, control structures, functions, file handling, and OOP. This prepares you for integrating Python with MongoDB in the next module.
