Introductory Python: syntax, variables and I/O, operators and precedence, decision and loop constructs, functions/modules/packages, lists/tuples/slicing, modular programs and CLI, OOP, exception and file handling, unittest/pdb testing and debugging.
2.6.1.1 Creating, Accessing, and Modifying Lists · Reviewed lesson · version 1 · published 16 Nov 2026
A list is created by placing items inside square brackets [ ], separated by commas. Lists can contain items of different types, such as numbers, strings, or even other lists.
2.5.1.5 Arbitrary Arguments · Reviewed lesson · version 1 · published 16 Nov 2026
Sometimes, you might not know how many arguments will be passed to your function. You can use *args and **kwargs to handle such cases.
Example: Define a function to add an arbitrary number of arguments.
python
defadd_numbers(*args):
returnsum(args) # sum( ) is a python function used to add the values of given argumentsprint(add_numbers(1, 2, 3)) # Output : 6print(add_numbers(4, 5)) # Output : 9
2.2.1.3 Creating Different Types of Variables
2.2.1.3 Creating Different Types of Variables · Reviewed lesson · version 1 · published 16 Nov 2026
In Python, you can create variables of different types to store various kinds of data. Here are some common types of variables:
Integer (int): Stores whole numbers. Example: age = 17
2.3.1 Arithmetic Operators · Reviewed lesson · version 1 · published 16 Nov 2026
Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, modulus, exponentiation, and floor division as shown in the following code. The code shows how to use basic arithmetic operations in Python.
python
# Define variablesa= 10b= 3# Perform all arithmetic operations on these numeric variables and print resultsprint(a, "+", b, "=", a + b) # Output: 10+3=13print(a, "*", b, " = ", a * b) # Output: 10 * 3 = 30
2.8.1.1 Defining Classes and Creating Objects
2.8.1.1 Defining Classes and Creating Objects · Reviewed lesson · version 1 · published 16 Nov 2026
In programming, we use classes as concepts to define what an object should be like.
python
# Define a class called ToyCarclassToyCar:
# The __init__ method in idealizes the object with specific attributesdef__init__(self , color, size , wheels) :
self.color = color# Color of the toy carself.size = size# Size of the toy carself.wheels = wheels# Number of wheels in toy car
2.6.3.3 Indexing and Slicing with Negative Indices
2.6.3.3 Indexing and Slicing with Negative Indices · Reviewed lesson · version 1 · published 16 Nov 2026
Negative indices count from the end of the sequence. For example, -1 refers to the last element, -2 refers to the second last element, and so on.
Example: Indexing and slicing with both positive and negative indices on a list.
python
# Create a list of fruitsfruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry " ]
# Indexingprint("First fruit:", fruits [0]) # Positive indexprint("Last fruit:", fruits [-1]) # Negative index# Slicing with positive indices
2.10.1 Testing
2.10.1 Testing · Reviewed lesson · version 1 · published 16 Nov 2026
Testing is the process of running your code with various inputs to check if it behaves as expected. The goal is to find and fix any issues before the code is used in real-world applications.
2.4.2.1 while Loop · Reviewed lesson · version 1 · published 16 Nov 2026
A while loop runs as long as a condition is true. It checks the condition before each iteration and stops running when the condition is no longer true.
python
# Syntax of while loop while condition:# code to run while the condition is true
Example: Add 1 to a number until it reaches 10.
python
number = 1whilenumber < 10:
print(number)
number += 1
Explanation: In this example, the code starts with a number set to 1. The 'while' loop checks if the number is less than 10. If it is, the program prints the current value of the number and then adds 1 to it. This loop continues until the number reaches 10, at which point the loop stops running.
2.8.1.2 Access Modifiers
2.8.1.2 Access Modifiers · Reviewed lesson · version 1 · published 16 Nov 2026
Access modifiers are keywords or mechanisms that define the accessibility of classes, methods, and variables. In python there are following access modifiers:
Public: Attributes and methods that are accessible from outside the class.
python
classCar:
def__init__(self , color): self.color = color# Public property
Protected: Attributes and methods are accessible within the class and its subclasses (derived classes).
python
2.9.1.2 Finally and Else
2.9.1.2 Finally and Else · Reviewed lesson · version 1 · published 16 Nov 2026
The finally block always executes, regardless of whether an exception was raised. The else block, if used, runs only if no exceptions were raised in the try block. These features are useful for ensuring certain code always runs and for executing additional logic when no errors occur.
python
try :
number = int(input("Enter a number"))
result = 10 / numberexceptZeroDivisionError:
print("You can’t divide by zero ! " )
exceptValueError:
print ("Invalid input! Please enter a valid number.")
else :
print ("The result is", result)
finally
2.7.2 Building CLI Applications
2.7.2 Building CLI Applications · Reviewed lesson · version 1 · published 16 Nov 2026
In this section, we explore CLI (Command-Line Interface) applications. These applications allow users to interact with a program through text commands in a terminal or command prompt. CLI applications can be developed using various programming languages, including Python. All the applications we develop in this chapter are, in fact, CLI applications. We can run each of them using the command line. So, let's run the application we created in section 2.7.1 using the command line. To run this application on command line interface we need to follow following steps.
Save the main. py and greetings. py files in the same directory.
Open your terminal or command prompt, navigate to the directory, and ran: python main.py.
You should see the output: As-Salaam-Alaikum, everyone!
2.5.1 Functions and Modules · Reviewed lesson · version 1 · published 16 Nov 2026
Functions and modules in Python are key to writing efficient and organized code. Functions allow you to encapsulate reusable blocks of code, while modules help you structure your program by grouping related functions together.
2.5.3.1 Module Search Path and Package Structure · Reviewed lesson · version 1 · published 16 Nov 2026
When you import a module in Python, the interpreter looks for it in a specific order. Let's explore each step with simple examples.
1.Current Directory: Python first checks the current directory where your script is located. Suppose you have a script named main. py in your folder along with a module helper. py.
Example: In helper.py:
python
defgreet () :
return" As – Salaam Alaikum from helper.py!"
In main.py:
python
importhelpermessage
2.9.1 Exception Handling
2.9.1 Exception Handling · Reviewed lesson · version 1 · published 16 Nov 2026
Exception handling is a mechanism to manage errors that occur during program execution. It allows a program to continue running or gracefully terminate if an error occurs, ensuring more robust and error-resilient code.
2.3.2 Comparison Operators · Reviewed lesson · version 1 · published 16 Nov 2026
Comparison operators are used to compare two values or expressions. They determine the relational logic between them, such as equality, inequality, greater than, less than, and so on. These operators return a boolean value (True or False) based on the comparison result. Here's a Python program that demonstrates the usage of all comparison operators.
python
# Define variablesx, y = 10, 5# Greater thanprint(x, ">", y, "=", x > y) # Output: 10 > 5 = True# Less thanprint(x, "<", y, "=", x <
2.4.2 Looping Constructs
2.4.2 Looping Constructs · Reviewed lesson · version 1 · published 16 Nov 2026
Loops help us repeat actions, making our code more efficient and easier to read. There are two main types of loops in Python: while loops and for loops.
2.8.1.6 Polymorphism · Reviewed lesson · version 1 · published 16 Nov 2026
Polymorphism refers to the ability of different objects to respond to the same method or function call in their own unique way. It allows one interface to be used for a general class of actions, with specific implementations based on the object.
This is useful for calling methods in a uniform way, even if different classes implement them differently.
Explanation: In the above code, animal_sound() can handle objects of different classes (Dog and Cat) uniformly.
2.9.1.3 Custom Exceptions
2.9.1.3 Custom Exceptions · Reviewed lesson · version 1 · published 16 Nov 2026
Custom exceptions allow you to define your own error types that can be raised and handled specifically.
python
classCustomError(Exception):
pass# pass statement is a placeholder that does nothing when executeddefcheck_value(value):
ifvalue < 0:
raiseCustomError("Value must be non-negative ! " )
try :
check_value(-1)
exceptCustomErrorase:
print("Error :"
2.6 Built-in Data Structures
2.6 Built-in Data Structures · Reviewed lesson · version 1 · published 16 Nov 2026
Python provides several built-in data structures that are essential for organizing and manipulating data efficiently. These include lists, tuples, and dictionaries, each offering unique features to handle various types of data and perform common operations.
2.8.1.4 Association · Reviewed lesson · version 1 · published 16 Nov 2026
Association represents a relationship between two classes. There are two types of association:
Aggregation: Represents a relationship where one class (e.g., Library) contains another class (e.g., Book) but does not own it. Books can exist independently of the library.
2.6.1.3 Modifying a List · Reviewed lesson · version 1 · published 16 Nov 2026
You can modify list items by accessing them via their index and assigning a new value. Example: Change the first item in the list to "Orange" and add a new fruit "Pineapple".
2.3.6 Operator Precedence in Python · Reviewed lesson · version 1 · published 16 Nov 2026
Operator precedence determines the order in which operations are performed in an expression. In Python as well as in Mathematics, certain operators have higher precedence and are evaluated before others. Understanding this helps ensure that your calculations are done correctly.
Parentheses '()': Highest precedence. Operations inside parentheses are performed first. (3 + 2) * 4 evaluates to 20.
Exponentiation: Performs power operations next.
2³ evaluates to 8.
Multiplication '*', Division '/', and Modulus '%': These operations come next. 4*3 evaluates to 12, 10/2 evaluates to 5.0 and 11%3 evaluates 2.
Addition '+' and Subtraction '-': These have lower precedence compared to multiplication and division.
5 + 2 evaluates to 7, and 10-4 evaluates to 6.
Example: Consider the expression 3 + 2*5. The multiplication is performed before the addition, so: 3 + 2*5 = 3 + 10 = 13
2.5.1.1 Defining and Invoking Functions · Reviewed lesson · version 1 · published 16 Nov 2026
Functions are defined using the def keyword, followed by the function name and parentheses which may include parameters. The body of the function contains the code to be executed and must be indented.
python
deffunction_name (parameters): # code to be executed
Example: Define a function to greet a person.
python
defgreet(name):
print("As-Salaam-Alaikum", name)
# Function invoking means call the function by name and perform the required task For example.greet
2.1.1.2 Setting Up Python Development Environment
2.1.1.2 Setting Up Python Development Environment · Reviewed lesson · version 1 · published 16 Nov 2026
The development environment refers to the process of preparing a computer to write, run, and debug Python code effectively. This involves installing and configuring the necessary software, tools, and libraries that make development smoother and more efficient. We can download and install Python from https: //www. python. org/. When starting with Python programming, choosing a good Integrated Development Environment (IDE) can help make coding easier.
2.7 Modular Programming in Python · Reviewed lesson · version 1 · published 16 Nov 2026
Modular programming is a technique used to divide a program into smaller, manageable, and reusable pieces called modules. By breaking a program into modules, developers can work on different parts independently and reuse code efficiently. This approach simplifies managing complex programs and promotes code reuse.
2.5 Python Modules and Built-in Data Structures · Reviewed lesson · version 1 · published 16 Nov 2026
Python offers an extensive standard library that includes numerous built-in modules and data structures. A data structure refers to a particular format or method for organizing and storing data. For example, a list is a data structure that we have previously utilized. In this section, we will examine the utilization of functions, modules, and libraries within Python.
2.10.1.1 Types of Testing · Reviewed lesson · version 1 · published 16 Nov 2026
Unit Testing: Tests individual parts of the code (like functions or classes) in isolation. Python's unittest module is commonly used for this.
Integration Testing: Checks how different parts of the code work together.
Functional Testing: Validates that the software behaves as expected from the user's perspective.
Regression Testing: Ensures that new changes don't break existing functionality. Example: In this example, we use the unittest module to test the add function. This ensures that the function returns the correct results by checking various input values.
python
importunittestdefadd (a , b) :
returna + bclassTestMathOperations(unittest.TestCase):
deftest_add(self):
2.6.1.4 Methods and Operations on Lists
2.6.1.4 Methods and Operations on Lists · Reviewed lesson · version 1 · published 16 Nov 2026
Python provides several built-in methods to work with lists. Here are a few useful ones:
append (item) - Adds an item to the end of the list.
remove (item) - Removes the first occurrence of an item from the list.
sort () - Sorts the list in ascending order.
reverse () - Reverses the order of the list.
Example: Add a new student to the list of students and then sort the list.
2.4 Control Structures · Reviewed lesson · version 1 · published 16 Nov 2026
In programming, we often need to control the flow of our program based on different conditions or repeat certain actions multiple times. This is where control structures come into play. There are two main types of control structures, Decision making and Looping:
2.4.1.4 if-elif-else Statement · Reviewed lesson · version 1 · published 16 Nov 2026
The if-elif-else statement allows us to check multiple conditions and execute different blocks of code for each condition.
python
# Syntax of if-elif-else statementifcondition1:
# code to run if condition1 is trueelifcondition2:
# code to run if condition2 is trueelse:
# code to run if none of the conditions are true
Example:
python
weather = "cloudy"# The output depends on the value stored in the variable” weather”if
2.2.1.5 Handling Integer and Float Inputs
2.2.1.5 Handling Integer and Float Inputs · Reviewed lesson · version 1 · published 16 Nov 2026
To handle numeric inputs, you typically use the int() or float() functions to convert input strings to integers or floating-point numbers, respectively.
Integer Inputs
python
# Example : Handling integer inputuser_age = int(input("Enter your age: "))
print("Your age is:",user_age)
2.6.2 Tuples · Reviewed lesson · version 1 · published 16 Nov 2026
In Python, tuples are a type of data structure used to store an ordered collection of items, similar to lists, but with a key difference: tuples are immutable, meaning their values cannot be changed after creation.
Example
python
# Creating a tuplemy_tuple = (1, 2, 3, "Hello", 4.5)
# Accessing elements by indexprint(my_tuple[0]) # Output: 1print(my_tuple[3]) # Output: Hello# Tuple lengthprint(len(my_tuple)) # Output: 5
2.1.1.1 Programming Basics
2.1.1.1 Programming Basics · Reviewed lesson · version 1 · published 16 Nov 2026
Computer programming involves the following basic steps to write a program.
Write Code: Create a set of instructions in a programming language.
Compile/Interpret: Translate the code into a form that the computer can understand.
Execute: Run the code to perform the task.
Output: Display the results or perform actions based on the code.
2.10.1.2 Debugging · Reviewed lesson · version 1 · published 16 Nov 2026
Debugging is the process of finding and fixing errors (bugs) in your code. It involves identifying the root cause of problems and making the necessary changes.
2.4.1 Decision Making · Reviewed lesson · version 1 · published 16 Nov 2026
Decision making in programming allows the program to choose different actions based on conditions. This is similar to how we make decisions in real life. Python provide variety of conditional statements to implement decision making. Below find the detailed implementation of python conditional statements.
2.8.1 Class and Objects · Reviewed lesson · version 1 · published 16 Nov 2026
A class is like a template for creating things, and an object is an actual thing created from that template. Imagine you want to make a toy car. You first need a blueprint or a template that describes how the toy car should look and function. This template includes details like:
Color
Size
Number of wheels
Type of material
The template is not an actual toy car; it's just a plan and it represents a class.
Using the template, you can create multiple toy cars. Each toy car made using the template will have its own specific characteristics, like different colors or sizes. These are the actual objects that you can play with. Each object is an instance of the class, meaning it follows the plan to have its own specific characteristics.
Summary · Reviewed lesson · version 1 · published 16 Nov 2026
In this chapter, we learn the essentials of Python programming, starting from the setup of your development environment to advanced programming techniques. We explored basic syntax, operators, and control structures, providing you with the tools to write effective Python code. You learned how to use functions, modules, and data structures to manage and manipulate data efficiently. We also introduced key concepts of modular programming and object-oriented programming. Lastly, we discussed exception handling, file operations, and debugging methods to help you troubleshoot and refine your code. With these skills, you are well-equipped to tackle more complex programming tasks and build robust Python CLI applications.
2.3.3 Assignment Operators · Reviewed lesson · version 1 · published 16 Nov 2026
Assignment operators are used to assign values to variables. The most common assignment operator is the equal sign (=), which assigns the value on the right to the variable on the left. There are also compound assignment operators like +=, -=, *=, and /=, which combine arithmetic operations with assignment.
2.8 Object-Oriented Programming in Python · Reviewed lesson · version 1 · published 16 Nov 2026
Object-Oriented Programming (OOP) is a way of designing and organizing code to make it easier to manage and understand. Imagine you're building a model city with toy blocks. In this city, each building, vehicle, and person is a separate entity that you can design and interact with.
2.4.2.3 The range() Function · Reviewed lesson · version 1 · published 16 Nov 2026
We can use the range() function to generate a sequence of numbers, which is often used in for loops.
python
# Syntax of range functionrange(stop)
range(start, stop)
range(start, stop, step)
Example: Print the numbers from 0 to 4.
python
foriinrange (5) :
print
Identifying Code Duplication and the main Function
Identifying Code Duplication; The main Function · Reviewed lesson · version 1 · published 16 Nov 2026
Identifying Code Duplication
Code duplication occurs when the same code is repeated in multiple places. This redundancy can lead to maintenance challenges and bugs. Identifying and eliminating code duplication is crucial for efficient modular programming.
The main Function
The main function in Python defines where the program should start. It's usually placed in a block that checks if the script is being run directly or imported as a module.
Example: Here's a simple example:
python
# main.pydefmain ( ) :
print("This is the main function.")
if__name__ == "__main__" :
main()
2.5.1.3 Default Parameters
2.5.1.3 Default Parameters · Reviewed lesson · version 1 · published 16 Nov 2026
Functions can have default parameter values, which are used if no argument is provided during the function call.
Example: Define a function with a default parameter.
Explanation: In this example, the greet function has a default parameter name set to "Student". If no argument is provided, it uses the default value.
2.4.1.2 if-else Statement
2.4.1.2 if-else Statement · Reviewed lesson · version 1 · published 16 Nov 2026
The if-else statement allows us to execute one block of code if a condition is true and another block if the condition is false.
python
# Syntax of if-else statement if condition:ifcondition:
# code to run if the condition is true else :else:
# code to run if the condition is false
Example:
python
temperature = 15iftemperature > 30:
print("It’s a hot day ")
else :
print
2.5.3 Importing and Using Libraries
2.5.3 Importing and Using Libraries · Reviewed lesson · version 1 · published 16 Nov 2026
Libraries are like pre-built toolkits that you can use without having to write all the code yourself. Let's explore how to import and use different libraries with some simple examples.
Example: Import the random library to generate random numbers.
python
importrandom# Generate a random number between 1 and 10number = random.randint(1, 10)
print("The random number is:", number)
Explanation: The random library helps you generate random numbers, which can be useful in games, simulations, or even to pick a winner in a lucky draw.
Example: Import the datetime library to work with dates and times,
2.5.2 Using Libraries and Modules
2.5.2 Using Libraries and Modules · Reviewed lesson · version 1 · published 16 Nov 2026
In Python, libraries and modules are like toolboxes full of useful tools that help you solve different problems without having to build everything from scratch. In this section, we explain how to import and use both standard and third-party libraries in your Python programs. We will also explore how Python searches for these modules and how they are organized in a package structure.
2.2.1.4 Input and Output Operations · Reviewed lesson · version 1 · published 16 Nov 2026
Input and output operations allow you to interact with the user. You can ask the user to enter data (input) and display information to the user (output).
Input: Use the input () function to get user input. The input () function displays a message on the screen and waits for the user to type something and press Enter. The text entered by the user is then stored in a variable. For example:
python
name = input("Enter your name: ")
This line of code asks the user to enter their name and stores it in the variable name.
Output: Use the print () function to display information on the screen. The print () function takes one or more arguments and displays them. For example:
python
2.9.1.1 Try-Except Blocks
2.9.1.1 Try-Except Blocks · Reviewed lesson · version 1 · published 16 Nov 2026
In Python, the try block lets you test a block of code for errors, and the except block lets you handle errors if occur.
Example:
python
Input atry :
result =10/a# This line creates error if the value of ‘a’ is 0exceptZeroDivisionError:
print("You can’t divide by zero!")
2.4.1.3 Short Hand if-else Statement
2.4.1.3 Short Hand if-else Statement · Reviewed lesson · version 1 · published 16 Nov 2026
Python also allows a short-hand if-else statement that can be written in a single line.
python
# Syntax of short hand if-else statementaction_if_trueifconditionelseaction_if_false
python
temperature = 15print("It’s a hot day") iftemperature > 30elseprint("It’s not a hot day")
2.2 Basic Python Syntax and Structure
2.2 Basic Python Syntax and Structure · Reviewed lesson · version 1 · published 16 Nov 2026
The following Python program demonstrates the simplicity and readability of the language:
python
print("As - Salaam-Alaikum, College Students!")
In this example, the print function is utilized to output the message enclosed in double quotation marks. This illustrates Python's straightforward syntax, where functions like print are used to perform actions such as displaying text.
Python Comments
Lines that are not executed by the Python interpreter. They are used to provide explanations or notes for the code. Single-line comments start with the # symbol while multi-line comments can be created using triple quotes (”') at the beginning and the end as shown below.
python
# This is a single - line commentprint ( "K2 is the second-highest mountain in the world "
2.3.4 Logical Operators
2.3.4 Logical Operators · Reviewed lesson · version 1 · published 16 Nov 2026
Logical operators are used to combine multiple conditions or expressions in a program. The most common logical operators are and. or, and not. They are used to perform logical operations and return Boolean values based on the evaluation of the expressions involved.
2.1.1 Understanding Basic Programming Concepts · Reviewed lesson · version 1 · published 16 Nov 2026
Computer programming is the process of creating a set of instructions that tell a computer how to perform a task. These instructions are written in a programming language that the computer can understand and execute. Think of computer programming like giving directions to a friend on how to reach your house. You need to be clear and precise so your friend doesn't get lost. Similarly, when we write programs, we give clear and precise instructions to the computer to complete specific tasks.
2.3 Operators and Expressions · Reviewed lesson · version 1 · published 16 Nov 2026
Operators are symbols that perform operations on variables and values. An expression is a combination of variables, operators, and values that produces a result. Let's explore different types of operators in Python.
2.9 Advanced Python Concepts · Reviewed lesson · version 1 · published 16 Nov 2026
Advanced Python concepts extend the foundational knowledge and empower programmers to handle more complex tasks effectively. This section covers key topics such as exception handling, which deals with managing errors gracefully, and file handling, which involves reading from and writing to files. Mastering these concepts is essential for developing robust and efficient Python applications.
2.6.1.2 Accessing List Items · Reviewed lesson · version 1 · published 16 Nov 2026
You can access items in a list by referring to their index, starting from 0. Example: Access and print the second item from the list of fruits.
python
fruits = ["Mango", "Apple", "Banana"]
print(fruits [1])
# Output: Apple
Explanation: The code initializes a list 'fruits' containing 'Mango', 'Apple', and 'Banana', then prints the second item, 'Apple', using the index ' 1 '.
2.2.1.1 Variable · Reviewed lesson · version 1 · published 16 Nov 2026
A variable in programming functions as a storage container within a computer's memory, allowing for the storage of data that can be retrieved and manipulated later in the code. In the example below, the variable age is utilized to hold numerical data. The value of a variable can change throughout the execution of a program, which is why it is referred to as a "variable":
python
print ( age ="As - Salaam-Alaikum , dear students ! ")age = 71print( "Quaid-i-Azam lived for", age, "years")
age =60print ( "Allama Iqbal lived for",
2.8.1.3 Constructor and Destructor
2.8.1.3 Constructor and Destructor · Reviewed lesson · version 1 · published 16 Nov 2026
Constructor: Constructor is a special type of function which is used to initialize the class variables. In Python the __init__() method is used to initialize an object's properties when it is created.
python
classCar:
def__init__(self , color):
self . color = color
Destructor: The __del__() method is called when an object is deleted. It is used for cleanup purposes.
python
classCar
2.4.1.5 Nested and Chained Conditionals
2.4.1.5 Nested and Chained Conditionals · Reviewed lesson · version 1 · published 16 Nov 2026
Sometimes, we need to check multiple conditions inside another condition. This is called nesting.
python
# Syntax of nested if statementifcondition1:
ifcondition2:
# code to run if both condition1 and condition2 are trueelse:
# code to run if condition1 is true but condition2 is falseelse:
# code to run if condition1 is false
Example: If the weather is rainy and the temperature is below 15 degrees, we wear a raincoat. If it is only rainy, we take an umbrella. If the weather is not rainy, we just enjoy the day.
python
weather = "rainy"
2.7.1 Working with Modules in Python
2.7.1 Working with Modules in Python · Reviewed lesson · version 1 · published 16 Nov 2026
A module in Python is just a file that contains Python code, such as functions, variables, and classes, which you can reuse in different parts of your program. Creating a module is easy. Just write your Python code in a file and save it with a .py extension. Here's how to create and use a module with the main, function:
2.6.3.2 Slicing · Reviewed lesson · version 1 · published 16 Nov 2026
Slicing allows you to access a subset of a sequence. The syntax for slicing is sequence [start: stop: step], where start is the starting index, stop is the ending index (not inclusive), and step is the step size.
2.10.1.3 Common Debugging Techniques · Reviewed lesson · version 1 · published 16 Nov 2026
Print Statements: Adding print statements to check the values of variables at different stages of the code.
Debugging Tools: Using tools like pdb (Python Debugger) to step through the code, inspect variables, and understand the flow of execution.
Error Messages: Reading and interpreting error messages to locate the source of the problem.
Example: In this example, the divide function is called with a zero denominator, causing a ZeroDivisionError. The try-except block catches the error and prints an error message, helping to identify and handle the issue.
python
defdivide(a, b) :
returna / btry :
result = divide (10 , 0)
exceptZeroDivisionErroras
2.5.1.2 Function Parameters and Return Values
2.5.1.2 Function Parameters and Return Values · Reviewed lesson · version 1 · published 16 Nov 2026
Functions can take multiple parameters and return values.
Example: Define a function to add two numbers.
python
defadd (a , b) : returna + b
Explanation: In this example, the add function takes two parameters a and b, and returns their sum.
2.9.1.6 Writing to Files · Reviewed lesson · version 1 · published 16 Nov 2026
To write to a file, open it in write mode (w) and use the write () method. To append data, use append mode (a).
python
# Writing to a filewithopen("example.txt", "w") asfile:
file.write("As-Salaam-Alaikum, World!\n")
# Appending to a filewithopen("example.txt", "a") asfile:
file.write("Appending new line.\n")
Explanation: In the above code:
2.8.1.5 Inheritance
2.8.1.5 Inheritance · Reviewed lesson · version 1 · published 16 Nov 2026
Inheritance allows one class to inherit attributes and methods from another class. This promotes code reuse and creates a hierarchical relationship between classes.
2.6.3.1 Indexing · Reviewed lesson · version 1 · published 16 Nov 2026
Indexing allows you to access individual elements in a sequence. Python uses zero-based indexing, meaning the first element has an index of 0, the second element has an index of 1. and so on.
2.1 Introduction to Python Programming · Reviewed lesson · version 1 · published 16 Nov 2026
Introduction
Welcome to the world of Python programming! Python is a popular, versatile language known for its simplicity and readability, making it ideal for both beginners and professionals. In this chapter, we will start with the basics, including setting up your development environment and learning fundamental programming concepts. As we move forward, we'll cover advanced topics like modular programming, file handling, debugging, and data structures. By the end of this chapter, you will have a comprehensive understanding of Python, enabling you to write, test, and debug your own programs and Command Line Interface(CLI) applications.
Python is a widely-used high-level programming language celebrated for its simplicity and readability. It is versatile and applicable to various fields, including web development, data analysis, artificial intelligence, and more. Python's straightforward syntax and clear structure make it an excellent choice for beginners, allowing them to focus on learning programming concepts rather than dealing with complex syntax rules. Whether you're creating a simple script or developing sophisticated software, Python's user-friendly nature helps you get started quickly and efficiently.
2.5.1.4 Keyword Arguments
2.5.1.4 Keyword Arguments · Reviewed lesson · version 1 · published 16 Nov 2026
You can call functions using keyword arguments, which makes the code more readable.
Example: Define a function with keyword arguments.
python
defintroduce(name , age) :
return"My name is " + name + " and I am " + str(age) + " years old."print(introduce(age =20, name = "Ali" )) # Output : My name is Ali and I am 20 years old.
Explanation: In this example, the introduce function is called using keyword arguments, specifying age first and then name.
2.3.5 Expressions
2.3.5 Expressions · Reviewed lesson · version 1 · published 16 Nov 2026
An expression is a combination of variables, operators, and values that produces a result. For example, 3 + 4 is an expression that results in 7. More complex expressions can use parentheses () to control the order of operations. For example:
python
result = (3 + 4) * 2# result is 14
BMI=heightweight
swipeBMI = weight / height
Explanation
: In this example, the add_numbers function takes a variable number of arguments using *args and returns their sum.
Class Definition: The “ToyCar” class is like the template for making toy cars. It describes what attributes a toy car should have: color, size, and wheels.
Creating Objects: “carl” and “car2” are specific toy cars created using the ToyCar template.Each has its own unique attributes.
Using Methods: The describe method allows us to get a description of the toy car.
Self: self is a convention used in object-oriented programming (OOP) to represent the instance of a class within its methods.
Explanation: This code demonstrates list operations in Python: creating a list of fruits, accessing elements using positive and negative indexing, and slicing the list with both positive and negative indices.
color is private, meaning it cannot be accessed directly outside the class. The method get_color () is used to access the private property.
Explanation: The first code snippet defines a 'Car' class with a public property 'color', accessible directly. The second snippet defines a 'Car' class with a private property '__color', which can only be accessed via the 'get_color()' method.
The else block runs only if no exceptions are raised, and it displays the result of the division. The finally block executes regardless of whether an exception occurred, ensuring that the completion message is printed.
Explanation: Since helper .py is in the same directory as main.py. Python successfully finds and imports it.
1.Standard Library: If Python doesn't find the module in the current directory, it moves on to the standard library, which contains many built-in modules. For example, if you want to generate random numbers, you can use the random module from the standard library.
Example: In main.py:
python
importrandomnumber = random.randint(1, 10)
print(f"Random number: {number}") # ‘f’ is used to place the value of a variable in a string# Output:# Random number: 7 (or any number between 1 and 10)
Explanation: Here, random is part of Python's standard library, so it is found without any issues.
Package Structure:
To manage large projects, you can organize modules into packages. A package is simply a directory containing related modules. For example, if you're building an e-commerce platform, you could create a package named ecommerce with modules like products .py, customers .py, and orders.py.
The above code demonstrates Python's comparison operators by defining two variables, x and y, and comparing them using various operators like >, <, ==, !=, >=, and <=.
“In programming, the hard part isn't solving problems, but deciding what problems to solve.” : Paul Graham
“Programming isn't about what you know; it's about what you can figure out.” :Chris Pine
Explanation: The above code made association by passing an instance of the 'Book' class to the 'Library' class through the 'add_book' method, which appends the book to the library's list of books.
Composition: Represents a relationship where one class (e.g., House) contains and owns another class (e.g.. Room). Rooms cannot exist without a house.
Explanation: The code demonstrates composition by creating a 'House' object that contains a list of 'Rooms' objects, each representing a room (like 'Living Room' and 'Bedroom'). The 'House' class depends on the 'Room' class to define its components.
Explanation: In this example, the greet function accepts a single parameter, name, with the value 'Ali'. It then prints a greeting message: 'As-Salaam-Alaikum Ali'.
Explanation: This code defines a unit test for the 'add' function, which sums two numbers. The 'TestMathOperations' class checks that 'add' correctly returns expected results for given inputs.
Explanation: In this example, the code checks multiple weather conditions. If the weather is “sunny”, the program prints ”Wear sunglasses”. If the weather is “rainy”, the program prints "Take an umbrella”. If the weather is neither “sunny” nor “rainy”, the program prints “Enjoy your day!”.
Explanation: In this example, the main() function will only run if the script is executed directly, not when it's imported elsewhere. This setup is useful in larger projects that have multiple modules.
importdatetime# Get the current date and timecurrent_time = datetime.datetime.now()
print("Current date and time:", current_time)
Explanation: The datetime library is very useful when you need to handle dates and times in your program, such as logging events or setting reminders.
Example: Import the statistics library to perform statistical calculations.
python
importstatistics# Calculate the mean of a list of numbersdata = [23, 45, 67, 89, 12, 44, 56]
mean_value = statistics.mean(data)
print("The mean value is:", mean_value)
Explanation: The statistics library is a great tool for performing basic statistical calculations, such as finding the mean, median, and mode of a set of data. This can be particularly useful in data analysis tasks.
In short by using these libraries, you can save time and effort, allowing you to focus on solving the specific problem at hand rather than reinventing the wheel.
Explanation: This is the same as the previous example but written in a more compact form. The output of the code depends on the value stored in the variable “temperature”, it prints “It's a hot day" if the value is greater than 30, otherwise it prints “It's not a hot day”.
The above code demonstrates the use of logical operators in Python. It defines two Boolean variables, x and y, and performs logical operations such as AND, OR, and NOT on them. The code also includes comments with the output of each logical operation.
This example illustrates how the variable "age" is assigned different values to represent the ages of Quaid-i-Azam Muhammad Ali Jinnah and Allama Iqbal, which are then printed as part of the output.
The destructor here prints a message when the object is deleted, indicating cleanup.
Explanation: The 'Car' class initializes with a 'color' attribute and prints a message when an instance is deleted, indicating the car with the given color is being removed.
Explanation: In this example, when you run main.py. Python imports the greetings module, calls the say_As-Salaam-Alaikum function, and prints the message. By organizing your program this way, you can use the greetings module in other parts of your application, and the main function clearly shows where your program begins.
Explanation: This code defines a function 'divide' that divides two numbers. It then tries to divide 10 by 0. which raises a 'ZeroDivisionError'. and catches this error to print a descriptive message.