Module 2 Python Programming & Foundations
Module 2 Python Programming & Foundations
AI Career Program
Module 2: Python Programming & Foundations
Variables & Data Input and Output Control Flow Loops (Iteration)
Types Communicating with the Decision making with for loops, while loops,
Storing and managing data user if/elif/else break, continue
Python is known for its simple syntax and readability, making it very
popular among beginners and professionals alike.
What is Python?
Programming languages allow humans to give instructions to computers in a readable format. Computers cannot understand human language
directly, so programming languages like Python help translate instructions into machine language.
The name "Python" was inspired by the British Instagram — Backend web infrastructure
comedy show Monty Python's Flying Circus. Facebook — Data analysis and automation
Python was designed with the goal of making Spotify — Music recommendation and analytics
programming easy to learn, readable, and efficient.
Features of Python
Because of these advantages, Python has become the most popular language for Artificial Intelligence and Machine Learning.
Applications of Python
Python was created by Guido van Python is widely used in AI, Web
Rossum and first released in 1991. Development, Data Science, and
Automation.
Part 2 — Installing Python and IDEs
Before writing Python programs, Python must be installed on your computer.
Python is available for Windows, Linux, and MacOS.
Expected output after installation: Python 3.12.1 — this confirms Python is installed successfully.
Installing Python on Linux & MacOS
Linux Installation MacOS Installation
1. Most Linux systems already include Python by 1. Download Python from the official website
default. 2. Run the installer package
2. To check: python3 --version 3. Follow the installation steps
3. To install: sudo apt install python3 4. Verify using: python3 --version
Introduction to IDEs
An IDE provides a code editor, syntax highlighting, debugging tools, and auto-completion — everything a developer needs in one place.
Environment variables allow the system to locate Python from any folder. If Python is added to the system PATH, you can run Python from the
terminal from any directory. Without setting PATH, the system may not recognise Python commands.
Running Python in Terminal & IDE
Running in Terminal Running in an IDE
Open Python interactive shell by typing python in the terminal. 1. Open VS Code or PyCharm
Python programs are saved as .py files. 2. Create a Python file with .py extension
Python files always use the .py extension. Example: [Link], [Link], [Link]
Part 2 — Key Points to Remember
Python must be installed before writing Python can run on Windows, Linux, and IDEs help developers write and run code
programs — download from the official MacOS — same code works across all easily with syntax highlighting and
Python website. platforms. debugging tools.
Popular IDEs include IDLE, VS Code, and Python programs can run in terminal or
PyCharm — each suited for different skill IDE and always use the .py extension.
levels.
Part 3 — Writing Your First
Python Script
A Python script is a file that contains Python code which can be executed by the
Python interpreter. Python programs are usually saved with the .py extension.
Output:
Hello Alice
Welcome to Python programming
Python Script Execution Flow
Execution
Script File
Program logic runs
Python .py source file sequentially
Interpreter Output
Reads and parses the Results displayed on
code screen
When you run a Python script, the Python interpreter reads the .py file line by line, processes each instruction, and displays the output on the screen. This
sequential execution makes Python easy to debug and understand.
Common Beginner Errors
1 2
3 4
Always double-check your spelling, parentheses, and file extension before running a Python script.
Part 4 — Python Syntax &
Comments
Syntax refers to the rules that define how Python code must be written. If the syntax
rules are not followed, the programme will produce an error. Python syntax is known
for being simple and easy to read.
if True: if True:
print("Hello") print("Hello") # ERROR!
age = 20
# age → variable name
# 20 → stored value
Rules for Naming Variables
1 2 3
name = "Alice"
age = 20
height = 5.5
is_student = True
age = 20
print(type(age))
Dynamic Typing
Output: <class 'int'>
Python uses dynamic typing — no need to specify data type explicitly.
The same variable can store different types.
Type Casting
x = 10 x = "10"
x = "Hello" # same variable! y = int(x) # String → Integer
print(y) → 10
num = 5
result = float(num) # Integer → Float
print(result) → 5.0
Variable and Data Storage Summary
4 0 1991
Core Data Types Type Declarations Needed Year Python Was Born
int, float, str, bool — the four fundamental data Python automatically detects the data type — Dynamic typing has been a core feature of
types in Python no explicit declaration required Python since its very first release
Use the type() function to check the data type of any variable. Use type casting functions like int(), float(), and str() to convert between
types.
Part 6 — Input and Output
In programming, Input and Output (I/O) refers to the communication between the
user and the programme. Input is data provided by the user, and output is
information displayed by the programme.
User Input
Program Processes
Display Output
The input() Function
The input() function is used to take input from the user. It always returns a string by default.
name = input("Enter your name: ") age = int(input("Enter your age: "))
print(name) print(age)
# Now the input becomes an integer
Output:
Enter your name: Alice Adding Two Numbers
Alice
f-strings are the recommended modern approach for string formatting in Python. They are cleaner, easier to read, and widely used in
professional code.
Complete Input/Output Example
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you are {age} years old")
Output:
Enter your name: Alice
Enter your age: 20
Hello Alice, you are 20 years old
input() is used to take input from the user — always returns a print() is used to display output on the screen.
string.
Type conversion (int(), float()) is required when working with f-strings provide a modern, clean way to format output with
numbers from input. variables embedded directly.
Part 7 - Control Flow
(Decision Making)
Control flow means controlling the order in which instructions
are executed. Python uses if, elif, and else statements to make
decisions based on conditions.
Example 1
If temperature is high → turn on the fan
Example 2
If marks are above 50 → student passes
Example 3
If password is correct → login allowed
if, if-else, and if-elif-else
if Statement if-elif-else — Grade System
Executes code only when a condition is true:
marks = 75
if marks >= 90:
age = 18
print("Grade A")
if age >= 18:
elif marks >= 70:
print("You are eligible to vote")
print("Grade B")
elif marks >= 50:
Output: You are eligible to vote
print("Grade C")
else:
if-else Statement print("Fail")
Control flow allows programmes to Python uses if, elif, and else for decision Nested if statements allow complex,
make decisions based on conditions. making — no switch statement needed. multi-level decision making in
programmes.
Part 8 — Loops (Iteration)
A loop is used to repeat a block of code multiple times. Loops are essential for
processing lists, printing sequences, and repeating calculations without writing the
same code over and over.
Repeating Calculations
Perform the same calculation multiple times with different values.
The for Loop
Used when we know how many times the loop should run. Commonly used with lists, strings, and ranges.
Output:
range() Function
apple
banana
range(5) → 0, 1, 2, 3, 4 mango
range(1,6) → 1, 2, 3, 4, 5
for i in range(1,6):
print(i)
Output: 1, 2, 3, 4, 5
The while Loop
The while loop runs as long as a condition remains true. It is useful when the number of iterations is not known in advance.
Output: 0, 1, 2, 3, 4 Output: 0, 1, 3, 4
(loop stops at 5) (2 is skipped)
for Loop vs while Loop
Feature for Loop while Loop
Output (for 5): 5, 10, 15, 20, 25, 30, 35, 40, 45, 50
Part 9 -
Functions, OOP & File Handling
This part covers three advanced and essential Python concepts: Functions for
reusable code, Object-Oriented Programming (OOP) for organised code structure,
and File Handling for storing and retrieving data.
Functions OOP
Reusable blocks of code that Organise code using classes and
perform specific tasks — organise objects — model real-world entities
and reduce repetition. in programmes.
File Handling
Store and retrieve data from files — make programmes persistent and data-
driven.
Functions in Python
A function is a reusable block of code that performs a specific task. Functions help in organising code, reducing repetition, and improving readability.
add = lambda a, b: a + b
greet("Alice")
print(add(4, 6))
Output: Hello Alice
Output: 10
Object-Oriented Programming (OOP)
OOP organises code using classes and objects. A class is a blueprint, and objects are instances of that class. Example: Class → Car; Objects → BMW, Tesla, Toyota.
Classes and Objects Inheritance
d = Dog()
Constructor (__init__)
[Link]()
Output: Animal makes sound
class Student:
def __init__(self, name):
[Link] = name
Polymorphism
class Cat:
def sound(self):
print("Meow")
d = Dog()
c = Cat()
[Link]() → Bark
[Link]() → Meow
OOP Concepts at a Glance
File Handling in Python
File handling allows programmes to store and retrieve data from files. This makes programmes persistent — data is saved even after the programme closes.
Mode Meaning
Writing to a File
The with statement is the recommended approach — it
automatically closes the file even if an error occurs.
file = open("[Link]", "w")
[Link]("Hello Python")
[Link]() Saving Student Data
Content saved: Hello Python
Polymorphism allows different behaviour for the same method File handling allows programmes to read and write files — use with
name across different classes. for safety.
Part 10 — Python Projects
(Basic to Advanced)
Projects help students improve logical thinking, practise programming skills, understand
real-world applications, and build a portfolio for future jobs.
Basic Concepts
1 Variables, I/O, conditions, loops
Beginner Projects
2 Calculator, Number Guessing Game
Intermediate Projects
3 Student Database, To-Do List
Advanced Apps
4 Login System, Table Generator
Project 1 — Basic Calculator
BEGINNER PROJECT
Concepts used: variables, input/output, conditions. Operations: addition, subtraction, multiplication, division.
if operation == "+":
print("Result:", num1 + num2)
elif operation == "-":
print("Result:", num1 - num2)
elif operation == "*":
print("Result:", num1 * num2)
elif operation == "/":
print("Result:", num1 / num2)
else:
print("Invalid operation")
Example Output:
Enter first number: 10
Enter second number: 5
Enter operation: *
Result: 50
Project 2 — Number Guessing Game
BEGINNER PROJECT
Concepts used: variables, input/output, conditions. A fun interactive programme where the user tries to guess a secret number.
secret_number = 7
guess = int(input("Guess the number: "))
if guess == secret_number:
print("Correct guess!")
else:
print("Wrong guess. Try again!")
Example Output:
Guess the number: 7
Correct guess!
This project can be extended with a while loop to allow multiple guesses until the user gets it right — a great intermediate challenge!
Project 3 — Student Database System
INTERMEDIATE PROJECT
Concepts used: loops, functions, file handling, data storage. This project saves student records to a text file for persistent storage.
Concepts used: lists, input/output, loops. This project demonstrates how to use Python lists to store and manage tasks dynamically.
tasks = []
task = input("Enter a task: ")
[Link](task)
print("Your tasks:", tasks)
Example Output:
Enter a task: Study Python
Your tasks: ['Study Python']
This project can be extended with a loop to keep adding tasks, options to delete tasks, and file handling to save the list permanently.
Project 5 — File-Based Login System
ADVANCED PROJECT
Concepts used: functions, conditions, file handling, loops. This project simulates a real-world login system using stored credentials.
Enter Success /
Check File
Credentials Fail
Concepts used: loops, input/output, arithmetic operations. A clean and practical programme that generates a full multiplication table for any
number.
Beginner Projects
Focus on basic concepts: variables, input/output, conditions, and simple loops.
Intermediate Projects
Introduce file handling and data storage — making programmes persistent and useful.
Advanced Projects
Simulate real-world applications — login systems, databases, and automation tools.
Congratulations on completing Module 2: Python Programming & Foundations. You have covered all
10 essential parts of Python — from installation and syntax to advanced concepts like OOP, file
handling, and real-world projects.
10 6
Parts Covered Projects Built
From Introduction to Python all the way to Calculator, Guessing Game, Database, To-Do List,
Advanced Projects Login System, Table Generator
4
Core Data Types
int, float, str, bool — the building blocks of all
Python programmes