Python is an interpreted, high-level programming language known for its simplicity and readability. It is widely used for web development, data analysis, machine learning, automation, and more.
Running Python:
- Interactive Mode (REPL): Start the Python interpreter to execute commands one by one.
- Script Mode: Write Python code in a .py file and execute the entire script.
Basic Syntax:
- Indentation is crucial in Python and used to define code blocks instead of curly braces.
- Comments start with the # symbol.
- Variables are assigned using =, without declaring data types.
- Print values using the print() function.
Data Types:
- int: Whole numbers (5, -10)
- float: Decimal numbers (3.14, -2.7)
- str: Sequence of characters ('Hello', "World")
- bool: True or False values
Documentation Strings:
These are multiline string literals that describe a module, function, class, or method.
Get started with Python by understanding its purpose, installing it, and writing basic code syntax.
Learning Objectives
Understand what Python is and where it is used
Install and run Python programs
Write and execute basic Python syntax
Key Topics
What is Python?
Running Python (REPL vs script)
Basic syntax rules and indentation
Variables and data types: int, float, string, boolean
Comments and documentation strings
Assessment Tasks
● Print 'Hello, World!'
● Create variables for name, age, and print a formatted message.
Detailed Lesson
Python is an interpreted, high-level programming language known for its simplicity and readability. It is widely used for web development, data analysis, machine learning, automation, and more.
Running Python:
- Interactive Mode (REPL): Start the Python interpreter to execute commands one by one.
- Script Mode: Write Python code in a .py file and execute the entire script.
Basic Syntax:
- Indentation is crucial in Python and used to define code blocks instead of curly braces.
- Comments start with the # symbol.
- Variables are assigned using =, without declaring data types.
- Print values using the print() function.
Data Types:
- int: Whole numbers (5, -10)
- float: Decimal numbers (3.14, -2.7)
- str: Sequence of characters ('Hello', "World")
- bool: True or False values
Documentation Strings:
These are multiline string literals that describe a module, function, class, or method.
Knowledge Check
Q1: What is the purpose of indentation in Python?
Indentation is used to define code blocks instead of curly braces in Python.
Q2: How do you print a value in Python?
Use the print() function to print values in Python.
Q3: What is the difference between an int and a float data type?
int represents whole numbers, while float represents decimal numbers.
Module 2
Control Flow and Logic
|
Conditional Statements:
- if statement: Executes a block of code if the condition is True.
- elif statement: Provides additional conditions to check if the previous conditions were False.
- else statement: Executes a block of code if all previous conditions were False.
Comparison Operators:
- == (equal to)
- != (not equal to)
- > (greater than)
- < (less than)
- >= (greater than or equal to)
- <= (less than or equal to)
Logical Operators:
- and: Returns True if both operands are True.
- or: Returns True if at least one operand is True.
- not: Negates the truth value of an operand.
Loops:
- for loop: Iterates over a sequence (list, string, range).
- while loop: Repeats a block of code as long as the condition is True.
- break: Exits the current loop.
- continue: Skips the current iteration and moves to the next one.
Learn how to control the flow of your Python programs using conditional statements, loops, and logical operators.
Learning Objectives
Use conditional statements
Implement loops
Apply logical operators
Key Topics
if, elif, else statements
Comparison operators (==, !=, >, <)
Logical operators (and, or, not)
for loops and while loops
break and continue
Assessment Tasks
● Build a number guessing game
● Print even numbers from 1 to 20
Detailed Lesson
Conditional Statements:
- if statement: Executes a block of code if the condition is True.
- elif statement: Provides additional conditions to check if the previous conditions were False.
- else statement: Executes a block of code if all previous conditions were False.
Comparison Operators:
- == (equal to)
- != (not equal to)
- > (greater than)
- < (less than)
- >= (greater than or equal to)
- <= (less than or equal to)
Logical Operators:
- and: Returns True if both operands are True.
- or: Returns True if at least one operand is True.
- not: Negates the truth value of an operand.
Loops:
- for loop: Iterates over a sequence (list, string, range).
- while loop: Repeats a block of code as long as the condition is True.
- break: Exits the current loop.
- continue: Skips the current iteration and moves to the next one.
Knowledge Check
Q1: What is the purpose of the elif statement?
The elif statement allows you to check additional conditions if the previous conditions were False.
Q2: What is the difference between the and and or logical operators?
The and operator returns True if both operands are True, while the or operator returns True if at least one operand is True.
Q3: How do you exit a loop prematurely in Python?
Use the break statement to exit a loop prematurely in Python.
Module 3
Functions and Modularity
|
Defining Functions:
- Use the def keyword followed by the function name and parentheses.
- Parameters are variables that accept values when the function is called.
- The function body is indented and contains the code to be executed.
Parameters and Arguments:
- Parameters are the variables defined in the function definition.
- Arguments are the actual values passed to the function when it is called.
Return Statements:
- The return statement is used to exit a function and return a value.
- A function without a return statement returns None by default.
Scope:
- Local scope: Variables defined inside a function are only accessible within that function.
- Global scope: Variables defined outside any function are accessible throughout the program.
Modular Scripts:
- Modular code is easier to maintain, reuse, and debug.
- Functions can be imported from other Python files using the import statement.
Learn how to create reusable functions, utilize parameters and return values, and understand scope in Python.
Learning Objectives
Define reusable functions
Use parameters and return values
Understand scope
Key Topics
def keyword
Parameters vs arguments
Return statements
Local vs global scope
Writing modular scripts
Assessment Tasks
● Create a function to calculate the area of a rectangle
● Build a simple calculator function
Detailed Lesson
Defining Functions:
- Use the def keyword followed by the function name and parentheses.
- Parameters are variables that accept values when the function is called.
- The function body is indented and contains the code to be executed.
Parameters and Arguments:
- Parameters are the variables defined in the function definition.
- Arguments are the actual values passed to the function when it is called.
Return Statements:
- The return statement is used to exit a function and return a value.
- A function without a return statement returns None by default.
Scope:
- Local scope: Variables defined inside a function are only accessible within that function.
- Global scope: Variables defined outside any function are accessible throughout the program.
Modular Scripts:
- Modular code is easier to maintain, reuse, and debug.
- Functions can be imported from other Python files using the import statement.
Knowledge Check
Q1: What is the difference between parameters and arguments in Python functions?
Parameters are the variables defined in the function definition, while arguments are the actual values passed to the function when it is called.
Q2: What does the return statement do in a Python function?
The return statement is used to exit a function and return a value.
Q3: Can variables defined inside a function be accessed outside of that function?
No, variables defined inside a function (local scope) cannot be accessed outside of that function.
Module 4
Data Structures
|
Lists:
- Ordered collection of items, mutable (can be changed).
- Access elements by index: my_list[0]
- Append, insert, remove, pop, sort, and reverse methods.
Tuples:
- Ordered collection of items, immutable (cannot be changed).
- Access elements by index: my_tuple[0]
- Used for data that should not be modified.
Dictionaries:
- Unordered collection of key-value pairs.
- Access values by key: my_dict['name']
- Add, update, and remove key-value pairs.
Sets:
- Unordered collection of unique elements.
- Add, remove, union, intersection, and difference methods.
- Used to remove duplicates from a list.
Iterating:
- for loop to iterate over elements.
- enumerate() to get both index and value.
Learn how to store and manipulate collections of data using various data structures in Python.
Learning Objectives
Store and manipulate collections of data
Key Topics
Lists (append, remove, indexing)
Tuples (immutable sequences)
Dictionaries (key-value pairs)
Sets (unique values)
Iterating through data structures
Assessment Tasks
● Store student scores in a list and calculate the average
● Create a dictionary of user profiles
Detailed Lesson
Lists:
- Ordered collection of items, mutable (can be changed).
- Access elements by index: my_list[0]
- Append, insert, remove, pop, sort, and reverse methods.
Tuples:
- Ordered collection of items, immutable (cannot be changed).
- Access elements by index: my_tuple[0]
- Used for data that should not be modified.
Dictionaries:
- Unordered collection of key-value pairs.
- Access values by key: my_dict['name']
- Add, update, and remove key-value pairs.
Sets:
- Unordered collection of unique elements.
- Add, remove, union, intersection, and difference methods.
- Used to remove duplicates from a list.
Iterating:
- for loop to iterate over elements.
- enumerate() to get both index and value.
Knowledge Check
Q1: What is the difference between a list and a tuple in Python?
A list is mutable (can be changed), while a tuple is immutable (cannot be changed).
Q2: How do you access the value associated with a key in a dictionary?
Use the key as an index to access the value: my_dict['key']
Q3: What is the purpose of a set in Python?
A set is used to store unique elements, and it can be useful for removing duplicates from a list.
Module 5
File Handling and Introduction to Libraries
|
File Operations:
- Open a file using open() function: file = open('file.txt', 'r')
- Read from a file: content = file.read()
- Write to a file: file.write('Hello, World!')
- Close a file: file.close()
File Modes:
- 'r' (read mode, default)
- 'w' (write mode, overwrites existing file)
- 'a' (append mode, adds to existing file)
- 'x' (create new file, fails if it exists)
Importing Libraries:
- Use the import statement to include external libraries.
- math: Mathematical functions (sqrt, sin, cos, etc.)
- random: Generate random numbers and sequences.
- datetime: Work with dates and times.
Examples:
- import math
- print(math.pi)
- import random
- print(random.randint(1, 10))
Learn how to read and write files in Python, and get an overview of commonly used libraries.
Learning Objectives
Read and write files
Import and use libraries
Key Topics
Opening and closing files
Reading text files
Writing to files
import statements
Overview of commonly used libraries (math, random, datetime)
Assessment Tasks
● Build a mini project that reads user input, stores results in a file, and generates a summary report.
Detailed Lesson
File Operations:
- Open a file using open() function: file = open('file.txt', 'r')
- Read from a file: content = file.read()
- Write to a file: file.write('Hello, World!')
- Close a file: file.close()
File Modes:
- 'r' (read mode, default)
- 'w' (write mode, overwrites existing file)
- 'a' (append mode, adds to existing file)
- 'x' (create new file, fails if it exists)
Importing Libraries:
- Use the import statement to include external libraries.
- math: Mathematical functions (sqrt, sin, cos, etc.)
- random: Generate random numbers and sequences.
- datetime: Work with dates and times.
Examples:
- import math
- print(math.pi)
- import random
- print(random.randint(1, 10))
Knowledge Check
Q1: What is the purpose of the open() function in Python?
The open() function is used to open a file for reading, writing, or both.
Q2: What is the difference between the 'r' and 'w' file modes?
'r' is the read mode (default), while 'w' is the write mode which overwrites the existing file.
Q3: How do you import and use a module in Python?
Use the import statement to include a module, then access its functions or variables using dot notation (module.function()).
Final Assessment
Mastery Check
Demonstrate your understanding and complete the module.