0% found this document useful (0 votes)
7 views37 pages

Inter 1 Computer Unit 2 Notes

This document outlines the student learning outcomes for a chapter on Python programming, detailing key concepts such as basic syntax, data types, operators, and control structures. It emphasizes the importance of Python as a versatile language suitable for various applications and provides guidelines for setting up a development environment. Additionally, it includes exercises and questions to reinforce understanding of programming fundamentals.

Uploaded by

fahadkazim387
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views37 pages

Inter 1 Computer Unit 2 Notes

This document outlines the student learning outcomes for a chapter on Python programming, detailing key concepts such as basic syntax, data types, operators, and control structures. It emphasizes the importance of Python as a versatile language suitable for various applications and provides guidelines for setting up a development environment. Additionally, it includes exercises and questions to reinforce understanding of programming fundamentals.

Uploaded by

fahadkazim387
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

s

Student Learning Outcomes

BY THE END OF THIS CHAPTER, STUDENTS WILL BE ABLE TO:

 Understand basic programming concepts and set up a Python development environment.

 Write and interpret basic Python syntax and structure, including variables, data types, and

input/output operations.

 Use various operators and expressions in Python, including arithmetic, comparison, and

logical operators.

 Implement control structures such as decision-making statements and loops in Python.

 Work with Python modules, functions, and built-in data structures like lists.

 Apply modular programming techniques and object-oriented programming concepts in

Python.

 Handle exceptions, perform file operations, and apply testing and debugging techniques in

Python.

UNIT– 2 3
1
INTRODUCTION
Python is popular and easy to learn programming language. In this unit you will learn the basics,
setup tools and explore key components.
Later, we will learn advanced topics like
 File handling
 Debugging
 Data structure
2.1 INTRODUCTION TO PYTHON PROGRAMMING
Python is versatile and applicable to various fields,
SHORT QUESTION
including web development, data
analysis, artificial intelligence, and more.
Python's straightforward syntax and clear What is the importance of python
structure make it an excellent choice for programming now a days?
beginners, allowing them to focus on learning
programming concepts rather than dealing with complex syntax rules.

Python is named after the British comedy series "Monty


Python's Flying Circus." not the snake!

2.1.1 UNDERSTANDING BASIC PROGRAMMING CONCEPTS


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.
[Link] PROGRAMMING BASICS
Computer programming involves the following basic
steps to write a program.
(i) Write Code
Create a set of instructions in a programming language. Introduction to python programming
(ii) Compile/Interpret
Translate the code into a form that the computer can understand.
(iii) Execute
Run the code to perform the task.
(iv) Output
Display the results or perform actions based on the code.
[Link] SETTING UP PYTHON DEVELOPMENT ENVIRONMENT
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.

When installing Python, make sure to check the box that says "Add
Python to PATH." This makes it easier to run Python from the command
line. We can also use online services to write and run Python program.

UNIT– 2 3
2
MULTIPLE CHOICE QUESTIONS
(1) Which is a popular, versatile language known for its simplicity and readability, making it
ideal for both beginners and professionals?
(A) B language (B) C language
(C) C++ language (D) Python language
(2) What is the origin of the name "Python" for the programming language?
(A) Named after snake (B) Named after scientist, Python Einstein
(C) Named after British comedy "Monty Python's Flying Circus"
(D) Named after Greek philosopher Pythagoras
(3) Who created the Python programming language?
(A) Bill Gates (B) James Gosling
(C) Guido van Rossum (D) Tim Berners-Lee
EXTENSIVE QUESTIONS

(1) Write a detail note on python programming that involves the basic steps to write a
program.

2.2 BASIC PYTHON SYNTAX AND STRUCTURE


The following Python program demonstrates the simplicity and readability of the language:
print ("This is my first page")
In this example, the print function is utilized to SHORT QUESTION
output the message enclosed in double
quotation marks. This illustrates Python's What is the role of comments in
straightforward syntax, where functions like python programming?
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
 multi-line comments can be created using triple quotes
(”') at the beginning and the end as shown below.
Basic python syntax and structure
# This is a single - line comment
print ("K2 is the second-highest mountain in the world")
,,,
This is a multi-line comment.
It can span multiple lines.
,,,
print ("Edhi Foundation is the largest volunteer ambulance network.")
2.2.1 VARIABLES, DATA TYPES AND INPUT/OUTPUT
[Link] VARIABLE
SHORT QUESTION
A variable is a storage container in a computer's
memory, that allows storage, retrieval an What are some common rules for
manipulation of data. The value of a variable can naming variable in python?
change throughout the execution of a program.
UNIT– 2 3
3
age = 71
print( "Ahmad lived for", age, "years")
age = 60
print ( "Iqbal lived for", age, "years")
[Link] VARIABLE NAMING RULES IN PYTHON
Variable names in Python must adhere to the following rules:
 The name must begin with a letter (a-z, A-Z) or an underscore (_).
 Subsequent characters can include letters, digits (0-9), or underscores ( _ ).
 Variable names are case-sensitive, meaning age and Age are considered two different variables.
 Python's reserved keywords, such as for, while, if, etc., cannot be used as variable names.

Always use meaningful names for variables to make your code easier to
understand. For example, use age instead of a.

[Link] CREATING DIFFERENT TYPES OF VARIABLES


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
 Floating-point (float): Stores decimal numbers.
Example price = 19.99
 String (str): Stores text.
Example name = "Ali"
 Boolean (bool): Stores True or False.
Example is student = True

It's a good practice to use lowercase letters and underscores to separate


words in variable names (e.g., student_name).

[Link] INPUT AND OUTPUT OPERATIONS


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). SHORT QUESTION
Input
Use the input () function to get user input. The What do you know about input and
input () function displays a message on the output operations in python
screen and waits for the user to type something programming?
and press Enter. The text entered by the user is
then stored in a variable.
Example
name = input ("Enter your name:")
Output
Use the print () function to display information on the screen. The print () function takes one or
more arguments and displays them.
Example
print ("Hello," + name + "!")
UNIT– 2 3
4
[Link] HANDLING INTEGER AND FLOAT INPUTS
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
# Example Handling integer input
user_age = int(input("Enter your age: "))
print("Your age is:",user_age)
Float Inputs
#Example Handling float input
user_height = float(input("Enter your height in meters: ") )
print("Your height is", user_height,"meter")
MULTIPLE CHOICE QUESTIONS
(1) Lines that are not executed by the Python interpreter is known as:
(A) Feedback (B) Explanatory notes (C) Comments (D) Keywords
(2) Which in programing work as a storage container within a computer’s memory?
(A) I/O functions (B) Variable (C) Constant (D) Data type
(3) Which function is used to convert user input into an integer in Python?
(A) float() (B) str() (C) int() (D) input()
EXTENSIVE QUESTIONS

(1) Explain the concept of variable in python. Write down the rules for naming variable.
(2) What are the basic data types in Python? Write in detail with example.

2.3 OPERATORS AND EXPRESSIONS


Operators are symbols that perform operations on variables and values. An expression is a
combination of variables, operators, and values that produces a result.
2.3.1 ARITHMETIC OPERATORS
Arithmetic operators are used to perform basic mathematical operations. Such as:
 addition
 subtraction
 multiplication
 Division
 Modulus
 Exponentiation
floor division as shown in the following code.
OPERATORS TYPE
+, -, *, /, % Arithmetic operator
<, <=, >, >=, = =, != Relational operator
AND, OR, NOT Logical operator
&, |, <<, >>, -, ^ Bitwise operator
=, +=, -=, *=, %= Assignment operator
# Define variables
a= 10 b= 3
# Perform all arithmetic operations
print(a, "+", b, "=", a + b) # Output: 10+3=13
print(a, "*", b, " = " , a * b) # Output: 10 * 3 = 30
print(a, "/", b, " = ", a / b)
UNIT– 2 3
5
# Output
10 / 3 = 3.3333333333333335
print(a, "//", " = b, a // b) "
# Output
10 // 3=3
print(a, "%", b, " = ", a % b)
# Output
10 % 3 = 1
print(a, "**", " = b, a ** b) "
# Output 10**3= 1000

A tutorial on Python is available at. [Link]

2.3.2 COMPARISON OPERATORS


Comparison operators are used to compare two
SHORT QUESTION
values or expressions. They determine the
relational logic between them, such as equality,
inequality, greater than, less than, and so on. What is the purpose of comparison
These operators return a boolean value (True or operator in programming?
False) based on the comparison result.
2.3.3 ASSIGNMENT OPERATORS
Assignment operators are used to assign values SHORT QUESTION
to variables. The most common assignment
operator is the equal sign (=), which assigns the How values are assigned using
value on the right to the variable on the left. assignment operators?
There are also compound assignment operators
like +=, -=, *=, and /=, which combine arithmetic operations with assignment.
#Define initial values
a = 10
b=5
# Assignment
assignment = a; print (“a = “, assignment)
#Output
a = 10
# Addition assignment
a +=b; print (“a after addition =”, a)
#Output
a = 15
# Subtraction assignment
a -=b; print (“a after subtraction =”, a)
#Output
a=5

# Multiplication assignment
a *=b; print (“a after multiplication =”, a)
#Output
a = 50
# Division assignment

UNIT– 2 3
6
a /=b; print (“a after division =”, a)
#Output
a = 2.0
# Modulus assignment
a %=b; print (“a after modulus division =”, a)
#Output
a=2
# Exponentiation assignment
a **=b; print (“a after modulus division =”, a)
#Output
a = 100000
2.3.4 LOGICAL OPERATORS
Logical operators are used to combine multiple SHORT QUESTION
conditions or expressions in a program. The
most common logical operators are and. or, and In which conditions logical operators
not. They are used to perform logical operations
are used?
and return Boolean values based on the
evaluation of the expressions involved.
# Define variables
x = True
y = False
# Logical AND
logical_and = x and y
print(x , "and ", y ,"=", logical_and)
# Output
True and False =False
# Logical OR
logical_or = x or y
print(x , "or " , y , " =", logical_or)
# Output
True and False = True
# Logical NOT
logical_not_x = not x
print("not", x, " = " , logical_not_x)
# Output
not True= False
2.3.5 EXPRESSIONS
An expression is a combination of variables, operators, and values that produces a result.
Example
3 + 4 is an expression that results in 7. More complex expressions can use parentheses () to
control the order of operations.
Example
result = (3 + 4) * 2 # result is 14

UNIT– 2 3
7
CLASS ACTIVITY
Write a program to calculate Body Mass Index (BMI). Ask the user for their weight and height,
then compute and display their BMI and classification. The Body Mass Index (BMI) is calculated
using the formula given below.
weight
BMI = height
where:
 weight is in kilograms (kg)
 height is in meters (m)

CLASS ACTIVITY SOLUTIONS


def calculate_bmi(): try:
# Get user input for weight and height
weight = float(input("Enter your weight in kilograms (kg): "))
height = float(input("Enter your height in meters (m): "))
# Check for valid positive inputs
if weight <= 0 or height <= 0:
print("Weight and height must be positive numbers.")
return
# Calculate BMI
bmi = weight / (height ** 2)
# Display BMI
print(f"\nYour BMI is: {bmi:.2f}")
# Classify BMI
if bmi < 18.5:
classification = "Underweight"
elif 18.5 <= bmi < 24.9:
classification = "Normal weight"
elif 25 <= bmi < 29.9:
classification = "Overweight"
else classification = "Obese"
print(f"Classification: {classification}")
except ValueError
print("Invalid input. Please enter numeric values for weight and height.")
# Run the BMI calculator
calculate_bmi()
2.3.6 OPERATOR PRECEDENCE IN PYTHON
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.
Parentheses '()':
Highest precedence. Operations inside parentheses are performed first. (3 + 2) * 4 evaluates to 20.
Exponentiation
Performs power operations next.
23 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.

UNIT– 2 3
8
5 + 2 evaluates to 7, and 10-4 evaluates to 6.
CLASS ACTIVITY
Compute the following expressions and compare results with your class fellows and class teacher.
1. 10 + 3*2 **2-5/5
2. (10 + 3) * (2 ** (2 - 1)) / 5
CLASS ACTIVITY SOLUTION
(1) 10 + 3*2**2 - 5/5
Step-by-step breakdown:
 2 ** 2 = 4
 3 * 4 = 12
 5 / 5 = 1.0
 10 + 12 - 1.0 = 21.0
Result: 21.0
(2) (10 + 3) * (2 ** (2 - 1)) / 5
Step-by-step breakdown:
 (10 + 3) = 13
 (2 - 1) = 1
 2 ** 1 = 2
 13 * 2 = 26
 26 / 5 = 5.2
Result: 5.2
EXPRESSION PYTHON VERSION RESULT
10 + 3*2**2 - 5/5 10 + 3 * 2 ** 2 - 5 / 5 21.0
(10 + 3) * (2 ** (2 - 1)) / 5 (10 + 3) * (2 ** (2 - 1)) / 5 5.2

Using parentheses can help clarify complex expressions and ensure the
operations are performed in the desired order.

MULTIPLE CHOICE QUESTIONS


(1) Which of the following is the correct operator to test equality in Python?
(A) = (B) = =
(C) = = = (D) Equal
(2) What is the output of the following code?
a = 10
b=3
print(a // b)
(A) 0 (B) 3
(C) 4 (D) 3.33
(3) Which of the following operators is used to multiply and assign in one step?
(A) *= (B) **=
(C) x= (D) /*

UNIT– 2 3
9
EXTENSIVE QUESTIONS

(1) Explain with examples how different types of operators work in Python, including
arithmetic, comparison, and logical operators.
(2) What is assignment operators? Demonstrate how compound assignment operators
simplify code? Explain.

SCENARIO-BASED QUESTION
Ali is writing a Python program to manage the scores of two players in a game. The initial scores
are score_player1 = 45 and score_player2 = 55. Each round, players gain or lose points. After
Round 1, Player 1 gains 15 points, and Player 2 loses 10 points.

He also wants to find:


 The difference in scores
 Whether Player 1 has overtaken Player 2
 If both players have scores above a minimum qualifying score of 50
 A final score multiplier applied only if both players qualified
SOLUTION
score_player1 = 45
score_player2 = 55
# Round 1 update
score_player1 += 15
score_player2 -= 10
# Difference in scores
difference = abs(score_player1 - score_player2)
print("Score difference:", difference)
# Check if Player 1 has overtaken Player 2
overtaken = score_player1 > score_player2
print("Has Player 1 overtaken Player 2?", overtaken)
# Check qualifications
qualified = score_player1 >= 50 and score_player2 >= 50
print("Both qualified:", qualified)

# Final score multiplier if qualified


if qualified
final_score_p1 = score_player1 * 1.1
final_score_p2 = score_player2 * 1.1
else final_score_p1 = score_player1
final_score_p2 = score_player2
print("Final Scores:", final_score_p1, final_score_p2)
2.4 CONTROL STRUCTURES
In programming, we often need to control the
SHORT QUESTION
flow of our program based on different
conditions or repeat certain actions multiple Why we use control structure in
programming?
times.

UNIT– 2 4
0
There are two main types of control structures:
 Decision making
 Looping
2.4.1 DECISION MAKING
Decision making in programming allows the program to choose different actions based on
conditions.
Python provide variety of conditional statements to implement decision making.
[Link] IF STATEMENT
The if statement lets us make decisions based on
conditions. If the condition is true, it runs a block
of code.
Syntax
# Syntax of if statement if condition:
if condition:
# code to run if the condition is true
Example Control structures
If the temperature is above 30 degrees, we print a
message. temperature = 35
[Link] IF-ELSE STATEMENT if temperature > 30:
The if-else statement allows us to execute one block of code if a print("It’s a hot day")
condition is true and another block if the condition is false.
Syntax
# Syntax of if-else statement if condition: temperature = 15
if condition: if temperature > 30:
# code to run if the condition is true else : print("It’s a hot day ")
else: # code to run if the condition is false
else:
Example print("It’s not a hot day " )
[Link] SHORT HAND IF-ELSE STATEMENT
Python also allows a short-hand if-else
temperature = 15
statement that can be written in a single line.
m = “it’s a hot day” if (temperature > 30)
Syntax
else “its not a hot day”
# Syntax of short hand if-else statement
print(m)
action_if_true if condition else action_if_false
CLASS ACTIVITY
Write an if-else statement and a short-hand if-else statement to check if a number is even or odd
and print the appropriate message.
CLASS ACTIVITY SOLUTION
Standard if-else Statement
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
Short-hand if-else Statement
number = int(input("Enter a number: "))
print(f"{number} is even." if number % 2 == 0 else f"{number} is odd.")
[Link] IF-ELIF-ELSE STATEMENT
The if-elif-else statement allows us to check multiple conditions and execute different blocks of
code for each condition.
Syntax

UNIT– 2 4
1
# Syntax of if-elif-else statement
if condition1:
# code to run if condition1 is true
elif condition2:
# code to run if condition2 is true
else
# code to run if none of the conditions are true
Example
weather = "cloudy" # The output depends on the value stored in the variable”
weather”
if weather == "sunny":
print("Wear sunglasses")
elif weather == "rainy":
print("Take an umbrella")
else: print("Enjoy your day!")
CLASS ACTIVITY
Write an if-elif-else statement to check if a number is positive, negative, or zero.
CLASS ACTIVITY SOLUTION
Python if-elif-else Statement
number = float(input("Enter a number: "))
if number > 0:
print(f"{number} is positive.")
elif number < 0:
print(f"{number} is negative.")
else:
print("The number is zero.")
2.4.2 LOOPING CONSTRUCTS
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.
[Link] WHILE LOOP
SHORT QUESTION
A while loop runs as long as a condition is true.
It checks the condition before each iteration and
Why programmer needs to repeat
stops running when the condition is no longer
statements in a program?
true.
Syntax
# Syntax of while loop while condition:
# code to run while the condition is true
Example
Add 1 to a number until it reaches 10.
number = 1
while number < 10:
print(number)
number += 1
CLASS ACTIVITY
Write a Python program that print even and count the odd numbers from 1 to 20 using a while
loop.
CLASS ACTIVITY SOLUTION
# Initialize variables
even_numbers = []
odd_count = 0
UNIT– 2 4
2
num = 1
# While loop to iterate from 1 to 20
while num <= 20:
if num % 2 == 0:
# Add even numbers to the list
even_numbers.append(num)

else:
# Count odd numbers
odd_count += 1
num += 1
# Print even numbers and count of odd numbers
print("Even numbers from 1 to 20:", even_numbers)
print("Count of odd numbers from 1 to 20:", odd_count)

[Link] FOR LOOP


A for loop repeats a block of code a specific number of times. It is commonly used to iterate over
a sequence (like a list, tuple, or string).
Syntax # Syntax of for loop
for variable in sequence:
# code to run for each element in the sequence
Example 1
Say “Hello” to each friend in a list of friends.
friends = ["Ahmad", "Ali", "Hassan"]
for friend in friends:
print("Hello", friend)
Explanation
In this example, the code goes through each friend in the list and prints a greeting message for
each one.
CLASS ACTIVITY
(1) Write a for loop using range() to print the even numbers from 2 to 10.
(2) Write a Python program that prints the first 10 multiples of 3 using a for loop and the
range() function.
CLASS ACTIVITY SOLUTION
(1) # Using range() to print even numbers from 2 to 10.
for num in range(2, 11, 2):
print(num)
(2) # Using range() to print the first 10 multiples of 3.
for num in range(3, 31, 3):
print(num)
MULTIPLE CHOICE QUESTIONS
(1) Which of the following is the correct syntax for an if statement in Python?
(A) if condition then: block (B) if condition: block
(C) if block: condition (D) if condition do: block
(2) What type of loop is best used when the number of iterations is unknown beforehand?
(A) for loop (B) do-while loop
(C) while loop (D) range loop
(3) What is the output of the following code?
number = 1
UNIT– 2 4
3
while number < 4:
print(number)
number += 1
(A) 0 1 2 (B) 1 2 3
(C) 1 2 3 4 (D) Infinite loop
EXTENSIVE QUESTIONS

(1) Explain the difference between the if-else and if-elif-else control structures in Python with
the help of program code examples.
(2) Write a Python program using a while loop that prints numbers from 1 to 20, but skips
printing the number 13.
(3) Discuss the use of a for loop in iterating through a list of students and checking if any
student has failed (assume pass mark is 40). Demonstrate how decision making and
looping are used together in this context.

SCENARIO-BASED QUESTION
You are writing a simple program for a weather station that records temperatures over a
week (7 days). The program should do the following:
(i) Ask the user to enter the temperature for each day.
(ii) After collecting all the temperatures, the program should:
Print a message for each day:
 If the temperature is above 30°C, print: "Day X: It's a hot day."
 If the temperature is between 20°C and 30°C, print: "Day X: It's a warm day."
 Otherwise, print: "Day X: It's a cool day."
SOLUTION
# Create an empty list to store temperatures
temperatures = []
# Collect temperature for 7 days
for day in range(1, 8):
temp = float(input(f"Enter the temperature for day {day}: "))
[Link](temp)
# Analyze and print a message for each day
for i in range(7):
temp = temperatures[i]
day = i + 1
if temp > 30:
print(f"Day {day}: It's a hot day.")
elif 20 <= temp <= 30:
print(f"Day {day}: It's a warm day.")
else:
print(f"Day {day}: It's a cool day.")

2.5 PYTHON MODULES AND BUILT-IN DATA STRUCTURES


Python offers an extensive standard library that
includes numerous built-in modules and
data structures. A data structure refers to a

UNIT– 2 4
4

Python modules and built-in data structures


particular format or method for organizing and storing data.
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.5.1 FUNCTIONS AND MODULES


Functions and modules in Python are key to SHORT QUESTION
writing efficient and organized code.
Functions allow you to encapsulate reusable How function is helpful to make
blocks of code, while modules help you program easier?
structure your program by grouping related
functions together.
[Link] DEFINING AND INVOKING FUNCTIONS
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.
Syntax
def function_name (parameters):
# code to be executed
Example
Define a function to greet a person.
def greet(name):
print("Hello", name)
# Function invoking means call the function by name and perform the required task.
greet (’Ali’)
[Link] FUNCTION PARAMETERS AND RETURN VALUES
Functions can take multiple parameters and return values.
Example
Define a function to add two numbers.
def add (a , b) :
return a + b

You can call a function multiple times with different arguments to reuse
the same code for different inputs.

[Link] DEFAULT PARAMETERS


Functions can have default parameter values, SHORT QUESTION
which are used if no argument is provided
during the function call. What is the purpose of default
parameters in python programming?
Example

UNIT– 2 4
5
Define a function with a default parameter.
def greet(name = "Student") :
return "Hello,"+ name +"!"
print(greet( ))
# Output
Hello, Student!
print(greet("Umer "))
# Output
Hello, Umer!

CLASS ACTIVITY
Define a function that takes a list of numbers and returns the maximum value.
CLASS ACTIVITY SOLUTION
def find_max(numbers):
# Return the maximum value in the list
return max(numbers)
# Example usage
numbers = [3, 5, 7, 2, 8, 10, 1]
max_value = find_max(numbers)
print("The maximum value is:", max_value)
2.5.2 USING LIBRARIES AND MODULES
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.
2.5.3 IMPORTING AND USING LIBRARIES
Libraries are like pre-built toolkits that you can use without having to write all the code yourself.
Example
Import the random library to generate random numbers.
import random
# Generate a random number between 1 and 10
number = [Link](1, 10)
print("The random number is:", number)
Import datetime
# Get the current date and time
current_time = [Link]()
print("Current date and time:", current_time)
Import statistics
# Calculate the mean of a list of numbers
data = [23, 45, 67, 89, 12, 44, 56]
mean_value = [Link](data)
print("The mean value is:", mean_value)
[Link] PACKAGE STRUCTURE
To manage large projects, you can organize modules into packages. A package is simply a
directory containing related modules.
Example
if you're building an e-commerce platform, you could create a package named ecommerce with
modules like products .py, customers .py, and [Link].
UNIT– 2 4
6
Example
In ecommerce/[Link]:
def 1ist_products () :
return ["Laptop","Mobile", "Tablet"]

In your main Script


from ecommerce import products
available_products = products.list_products()
print(available_products)

# Output
# [’Laptop’, ’Mobile’, ’Tablet’]
Explanation
In this case, ecommerce is the package, and [Link] is the module. This structure helps you
keep your code organized and manageable.

Organizing your modules into packages is like organizing books into


sections of a library—it makes finding and maintaining your code
much easier.

MULTIPLE CHOICE QUESTIONS


(1) What is the main purpose of using functions in Python?
(A) Create complex algorithms (B) Encapsulate reusable blocks of code
(C) Define modules (D) Compile the program
(2) Which keyword is used to define a function in Python?
(A) def (B) include
(C) define (D) function
(3) Which of the following is the correct way to import the random library in Python?
(A) import random as r (B) from random import *
(C) import random (D) import random_library

EXTENSIVE QUESTIONS

(1) Discuss how Python’s functions, modules, and libraries contribute to writing efficient and
maintainable programs.

2.6 BUILT-IN DATA STRUCTURES


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 SHORT QUESTION
various types of data and perform common
operations. Why we use list in python
2.6.1 LISTS programming?
In Python, a list is a versatile data structure that
can hold a collection of items. You can create, access, and modify lists easily.
[Link] CREATING, ACCESSING, AND MODIFYING LISTS

UNIT– 2 4
7
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.
Example

Create a list of your favorite fruits.


fruits = ["Mango", "Apple" "Banana"]
print(fruits)
# Output Creating, accessing, and modifying lists
[‘Mango’ ‘Apple ’ ‘Banana ’ ]
2.6.1 ACCESSING LIST ITEMS
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.
fruits = ["Mango", ”Apple”, “” Banana”[
print(fruits [1])
# Output
Apple
Explanation
The code initializes a list ‘fruit’ containing 'Mango', 'Apple', and 'Banana', then prints the second
item, 'Apple', using the index ' 1 '.
[Link] MODIFYING A LIST
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".
fruits = ["Mango", "Apple", "Banana"]
fruits [0] = "Orange"
[Link]("Pineapple")
print(fruits)
# Output
[’Orange’, ’Apple’, ’Banana’, ’Pineapple’]
Explanation
The code modifies the first element of the 'fruits' list to 'Orange', appends 'Pineapple' at the end,
and prints the updated list.
[Link] METHODS AND OPERATIONS ON LISTS
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

UNIT– 2 4
8
Add a new student to the list of students and then sort the list.
students = ["Ahmed", "Sara", "Ali"]
[Link]("Hina")
[Link] ()
print(students)
# Output
[‘Ahmed’, ‘Ali’, ‘Hina’, ‘Sara’]
Explanation
The code creates a list of students, adds 'Hina' to it, sorts the list alphabetically.
[Link] LIST OPERATIONS
Lists also support various operations, such as slicing and concatenation.

Example
Slice a portion of the list and concatenate it with another list.
numbers = [1, 2, 3, 4, 5]
slice = numbers [1:4] # Gets items from index 1 to 3
extra_numbers = [6, 7]
combined = slice + extra_numbers
print(combined)
# Output
[2, 3, 4, 6, 7]
Explanation
The code slices the 'numbers' list from index 1 to 3, combines it with 'extra_numbers', and prints
the resulting list '[2, 3, 4, 6. 7]'.
Example
Sort a list of student names and remove a specific name.
student _names= ["Ahmed", "Sara", "Ali", "Hina"]
student_names .sort ()
student_names . remove("Sara ")
print(student _names)
# Output
[’Ahmed ’ , ’ Ali’, ’Hina ’ ]
Explanation
The code sorts the list 'student_names' alphabetically, removes 'Sara' from the list, and then prints
the updated list.

Use list methods like append () and remove () to efficiently manage


and modify your lists.
For larger projects, organizing data in lists helps keep your code
clean and manageable.

CLASS ACTIVITY
Imagine you are maintaining a list of your favorite books: ["To Kill a Mockingbird", "1984", "The
Great Gatsby", "Pride and Prejudice"]. Perform the following tasks using Python:
UNIT– 2 4
9
(1) Add a new book "Moby Dick" to the list.
(2) Replace ”1984" with "Brave New World".
(3) Remove "The Great Gatsby" from the list.
(4) Merge this list with another list of books: ["War and Peace", "Hamlet"].
(5) Print the final list of books.
CLASS ACTIVITY SOLUTION
# Initial list of favorite books
books = ["To Kill a Mockingbird", "1984", "The Great Gatsby", "Pride and Prejudice"]
(1) # Add a new book "Moby Dick" to the list
[Link]("Moby Dick")
(2) # Replace "1984" with "Brave New World"
index = [Link]("1984")
books[index] = "Brave New World"

(3) # Remove "The Great Gatsby" from the list


[Link]("The Great Gatsby")
(4) # Merge this list with another list of books
more_books = ["War and Peace", "Hamlet"]
[Link](more_books)
(5) # Print the final list of books
print("Final list of favorite books:")
print(books)
Output Final list of favorite books:
['To Kill a Mockingbird', 'Brave New World', 'Pride and Prejudice', 'Moby Dick', 'War
and Peace',
2.6.2 TUPLES
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
2.6.3 INDEXING AND SLICING
Indexing and slicing are essential techniques # Creating a tuple
in Python for accessing and manipulating my_tuple = (1, 2, 3, "Hello", 4.5)
sequences such as lists, tuples, and strings. # Accessing elements by index
[Link] INDEXING print(my_tuple[0])
Indexing allows you to access individual # Output
elements in a sequence. Python uses zero- 1
based indexing, meaning the first element has print(my_tuple[3])
an index of 0, the second element has an index # Output
of 1. and so on. Hello
[Link] SLICING # Tuple length
Slicing allows you to access a subset of a print(len(my_tuple))
sequence. The syntax for slicing is sequence # Output
[start: stop: step], where start is the starting 5
index, stop is the ending index (not inclusive),
and step is the step size.
[Link] INDEXING AND SLICING WITH NEGATIVE INDICES
Negative indices count from the end of the sequence.
Example
-1 refers to the last element, -2 refers to the second last element, and so on.
Example
UNIT– 2 5
0
Explanation
This code
demonstrates list Indexing and slicing with both positive and negative indices on a
operations in Python: list.
creating a list of # Create a list of fruits
fruits, accessing fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry " ]
elements using # Indexing
positive and negative print("First fruit:", fruits [0]) # Positive index
indexing, and slicing print("Last fruit:", fruits [-1]) # Negative index
the list with both # Slicing with positive indices
positive and negative print("Fruits from index 1 to 3:", fruits[1:4])
indices. # Slicing with negative indices
print("Fruits from index -4 to -1:", fruits [-4 : - 1] )

UNIT– 2 5
1
CLASS ACTIVITY
Consider the following list, tuple, and string:
# List: [10, 20, 30, 40, 50, 60, 70, 80]
# Tuple: ("Math", "Science", "English", "History", "Geography")
# String: "Python Programming"
Perform the following operations:
(1) Access and print the third element from each sequence (list, tuple, and string).
(2) Slice and print elements from index 2 to 5 from the list and the tuple.
(3) Slice and print characters from index 7 to the end of the string.
(4) Use negative indexing to print the last two elements from the list and the tuple.
(5) Use negative slicing to print characters from the second last to the last character of
the string.
Write the Python code to perform these operations and print the results.
CLASS ACTIVITY SOLUTIONS
# Given Sequences
my_list = [10, 20, 30, 40, 50, 60, 70, 80]
my_tuple = ("Math", "Science", "English", "History", "Geography")
my_string = "Python Programming"
(1) #Access and print the third element (index 2)
print("Third element of the list:", my_list[2])
print("Third element of the tuple:", my_tuple[2])
print("Third character of the string:", my_string[2])
(2) # Slice and print elements from index 2 to 5 (index 2, 3, 4)
print("List elements from index 2 to 5:", my_list[2:5])
print("Tuple elements from index 2 to 5:", my_tuple[2:5])
(3) # Slice and print characters from index 7 to the end
print("String from index 7 to end:", my_string[7:])
(4) # Use negative indexing to print the last two elements
print("Last two elements of the list:", my_list[-2:])
print("Last two elements of the tuple:", my_tuple[-2:])
(5) # Negative slicing: second last to last character of the string
print("Second last to last character of the string:", my_string[-2:])
#Output
Third element of the list: 30
Third element of the tuple: English
Third character of the string: t
List elements from index 2 to 5: [30, 40, 50]
Tuple elements from index 2 to 5: ('English', 'History', 'Geography')
String from index 7 to end: Programming
Last two elements of the list: [70, 80]
Last two elements of the tuple: ('History', 'Geography')
Second last to last character of the string: ng

Indexing and slicing are powerful tools for working with sequences in
Python. Practice these techniques to become more proficient in
manipulating data and accessing specific parts of sequences.

UNIT– 2 5
2
MULTIPLE CHOICE QUESTIONS
(1) Which of the following is a valid way to create a list in Python?
(A) fruits = {“Mango”, “Apple”, “Banana”} (B) fruits = (“Mango”, “Apple”, “Banana”)
(C) fruits = [“Mango”, “Apple”, “Banana”] (D) fruits = <“Mango”, “Apple”, “Banana”>
(2) Which method adds an element at the end of a list?
(A) insert() (B) add()
(C) append() (D) extend()
(3) Which operation is used to combine two lists in Python?
(A) * (B) &
(C) + (D) combine()
EXTENSIVE QUESTIONS

(1) Explain the difference between lists and tuples in Python. Provide examples of their usage
and discuss their advantages in specific scenarios.
(2) Describe the process of indexing and slicing in Python, providing examples of both positive
and negative indexing.

2.7 MODULAR PROGRAMMING IN PYTHON


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 SHORT QUESTION
can work on different parts independently and
reuse code efficiently. This approach simplifies Why programmer prefer modular
managing complex programs and promotes code programming for solving a task?
reuse.
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:
# [Link]
def main ( ) :
print("This is the main function.")
if __name__ == "__main__" :
main()
Modular programming in python
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.

Using the main function with modules helps keep your code
organized, making it easier to maintain. Always use the main function
to define the starting point of your program, and use modules to
separate different parts of your code.

UNIT– 2 5
3
Python's standard library is made up of hundreds of modules that you
can use to perform common tasks, like working with dates, generating
random numbers, or reading files.

CLASS ACTIVITY
Create a Python module named calculator .py that includes two functions:
(1) add (a, b) - This function should return the sum of two numbers.
(2) subtract (a, b) - This function should return the difference between two numbers. Then,
write a script named main. py that imports your calculator module and uses these functions
to perform the following:
(a) Print the result of adding 15 and 8.
(b) Print the result of subtracting 10 from 25.
Make sure to run your main. py script and verify that the output is correct.
CLASS ACTIVITY SOLUTION
(1) add (a, b) -
Here's your complete [Link] module with the add(a, b) function:
# [Link]
def add(a, b):
"""
Return the sum of two numbers.
Parameters
a (int or float): The first number.
b (int or float): The second number.
Returns
int or float: The result of adding a and b.
"""
return a + b
import calculator
print([Link](10, 5))
# Output 15
(2) subtract (a, b) -
Step 1: Update [Link]
Add the subtract(a, b) function alongside the add(a, b) function:
# [Link]
def add(a, b):
"""
Return the sum of two numbers.
"""
return a + b
def subtract(a, b):
"""
Return the difference between two numbers.
"""
return a - b
Step 2: Create [Link]
This script will import the calculator module and call both functions:
# [Link]
import calculator

UNIT– 2 5
4
# a. Add 15 and 8
sum_result = [Link](15, 8)
print("15 + 8 =", sum_result)
# b. Subtract 10 from 25
diff_result = [Link](25, 10)
print("25 - 10 =", diff_result)
Step 3: Run the Script
To run the script and see the output, open a terminal or command prompt and run:
bash
python [Link]
Expected Output
15 + 8 = 23
25 - 10 = 15
MULTIPLE CHOICE QUESTIONS
(1) In the given example, which Python file contains the main function?
(A) [Link] (B) [Link]
(C) [Link] and [Link] (D) [Link] and [Link]
(2) What will the output of the code in [Link] be when run?
(A) As-Salaam-Alaikum, everyone! (B) Hello, World!
(C) World, Hello! (D) Error in code
(3) What is the purpose of the if __name__ == "__main__": block in Python?
(A) define the main function
(B) define global variables
(C) handle exceptions in Python
(D) check if the script is being run as the main program or imported as a module
2.8 OBJECT-ORIENTED PROGRAMMING IN PYTHON
Object-Oriented Programming (OOP) is a way of designing and organizing code to make it
easier to manage and understand.
2.8.1 CLASS AND OBJECTS
SHORT QUESTION
A class is like a template for creating things, and
an object is an actual thing created from How would you differentiate between
that template. Imagine you want to make a toy class and object?
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 Object-oriented programming
in python
have its own specific characteristics.

UNIT– 2 5
5
[Link] DEFINING CLASSES AND CREATING OBJECTS
In programming, we use classes as concepts to define what an object should be like.
# Define a class called ToyCar
class ToyCar:
# The _init_ method initializes the object with specific attributes
def_init_(self, color, size, wheels):
[Link] = color # Color of the toy car
[Link] = size # Size of the toy car
[Link] = wheels # Number of wheels in the toy car
# Method to describe the toy car
def describe(self):
return f" This toy car is {[Link]}, size {[Link]}, and has {[Link]}, wheels.”
# Create objects of the ToyCar class
car1 = ToyCar(“red”, “small”, 4)
car2 = ToyCar("blue", "large", 6)
# Print descriptions of the toy cars
print([Link]())
print([Link]())
Explanation
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 [Link] 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.
MULTIPLE CHOICE QUESTIONS
(1) A class is like a:
(A) Variable (B) Template
(C) Loop (D) Module
(2) An object is:
(A) A function (B) A blueprint
(C) An instance of a class (D) A loop
(3) Which method initializes an object?
(A) start() (B) create__()
(C) init__() (D) setup__()
EXTENSIVE QUESTIONS

(1) Write a detail note on classes and objects in python. Give suitable with example.

UNIT– 2 5
6
2.9 ADVANCED PYTHON CONCEPTS
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, Advanced Python concepts
which involves reading from and writing to
files. Mastering these concepts is essential for developing robust and efficient Python
applications.
2.9.1 EXCEPTION HANDLING
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.
[Link] TRY-EXCEPT BLOCKS
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
Input a
try:
result =10/a
# This line creates error if the value of ‘a’ is 0
except ZeroDivisionError:
print("You can’t divide by zero!")
Explanation
 The try block contains code that might cause an error.
 The except block catches the Zero Division Error and handles it by printing a message.
[Link] FILE HANDLING
File handling involves reading from and writing to files. It is essential for storing
data persistently.
[Link] OPENING, READING, AND CLOSING FILES
To read a file, open it using the open() function, read its contents, and then close the file to free up
resources.
# Open and read a file SHORT QUESTION
with open("[Link]", "r") as file:
content = fi[Link] () How file can be handled in python
print(content) language?
Explanation
 The with statement ensures that the file is properly closed after its suite finishes, even if an error occurs.
 The file is opened in read mode (r), read contents into content, and then printed.
 The file opened using 'with' is automatically closed.
[Link] WRITING TO FILES
To write to a file, open it in write mode (w) and use the write () method. To append data, use
append mode (a).

UNIT– 2 5
7
# Writing to a file
with open("[Link]", "w") as file:
fi[Link]("As-Salaam-Alaikum, World!\n")
# Appending to a file
with open("[Link]", "a") as file:
fi[Link]("Appending new line.\n")
Explanation
 The file is opened in write mode (w) to overwrite its contents and write new data.
 The file is opened in append mode (a) to add data without overwriting existing content.
MULTIPLE CHOICE QUESTIONS
(1) Which file mode both reads and writes without truncating content?
(A) w (B) r (C) r+ (D) a
(2) Which block runs only if no exception occurs in try?
(A) finally (B) else (C) except (D) catch
(3) What is raised in the code 10 / 0?
(A) NameError (B) ValueError (C) DivisionbyZeroError (D) IndexError
EXTENSIVE QUESTIONS

(1) What is file handling? Explain the working of opening reading, writing, and closing a
file in python with example.

2.10 TESTING AND DEBUGGING IN PYTHON


In Python programming, testing and debugging are essential practices to ensure that your code
works correctly and efficiently.
2.10.1 TESTING SHORT QUESTION
Testing is the process of running your code with
various inputs to check if it behaves as expected. Why we need to test a program before
The goal is to find and fix any issues before the execution?
code is used in real-world applications.
2.10.1.1TYPES OF TESTING
 Unit Testing Tests individual parts of the code (like
functions or classes) in isolation. Python's unit-test module
is commonly used for this.
 Integration Testing Checks how different parts of the
code work together. Testing and Debugging in Python
 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.
2.10.1.2DEBUGGING
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.
[Link] COMMON DEBUGGING TECHNIQUES
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.
MULTIPLE CHOICE QUESTIONS
(1) What is the primary goal of testing in Python?
UNIT– 2 5
8
(A) Identify syntax errors (B) Code behaves as expected
(C) Code more complex (D) Increase the execution code
(2) Which of the following is a type of testing that checks individual parts of the code, such as
functions or classes?
(A) Integration Testing (B) Unit Testing (C) Functional Testing (D) Regression Testing
(3) What module is commonly used for unit testing in Python?
(A) debug (B) unit test (C) testutils (D) pytests
TEXT BOOK EXERCISE (SOLUTION)
Q.1 Multiple Choice Questions.

(1) An action needed during Python installation to run from the command line easily:
(A) Uncheck "Add Python to PATH" (B) Choose a different IDE
(C) Check "Add Python to PATH" (D) Install only the IDE
(2) A valid variable name in Python is:
(A) variablel1 (B) 1variable
(C) variable-name (D) variable name
(3) Output of following piece of code is:
age = 25;
print (" Age : " , age)
(A) Age: 25 (B) 25
(C) Age (D) age
(4) The operator used for exponentiation in Python is:
(A) * (B) **
(C) // (D) /
(5) A loop used to iterate over a collection such as lists is:
(A) while (B) for
(C) do-while (D) repeat
(6) A range() function used to generate a sequence of numbers:
(A) Generates a list of numbers (B) Creates a sequence of numbers
(C) Calculates the sum of numbers (D) Prints a range of numbers
(7) A keyword used to define a function in Python?
(A) define (B) function
(C) def (D) func
(8) What is the output of the following code?
temperature, humidity, wind_speed = 25, 60, 15
print("Hot and humid" if temperature > 30 and humidity > 50 else
"Warm and breezy" if temperature == 25 and wind_speed > 10 else
"Cool and dry" if temperature < 20 and humidity < 30 else "Moderate ")
(A) Hot (B) Warm
(C) Cool (D) Nothing
(9) The operation used to combine two lists in Python?

UNIT– 2 5
9
(A) combine() (B) concat()
(C) + (D) merge ()
ANSWER KEY

1 C 2 A 3 A 4 B 5 B
6 D 7 C 8 B 9 C
TEXT BOOK SHORT QUESTIONS
(1) Explain the purpose of using comments in Python code?
Ans: Lines that are not executed by the Python interpreter. They are used to provide explanations or
notes for the code. They make the program easier to understand for others and for yourself.
Python ignores comments when running the code, so they don’t affect the output. They are
helpful for adding notes or reminders in 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.
# This is a single - line comment
print ( "K2 is the second-highest mountain in the world " )
,,,
This is a multi-line comment.
It can span multiple lines.
,,,
print ("Edhi Foundation operates the world's largest volunteer ambulance network." )
Purpose of Using Comments in Python
 Improve Readability
 Document Code
 Debugging Aid
 Collaboration
 Future Reference
(2) Describe the difference between integer and float data types in Python. Provide an example of
each.
Ans: Following are the differences between integer and float data types.
INTEGER DATA TYPES FLOAT DATA TYPES
Definition
Integer is a whole number without a decimal Float is a number with a decimal point (fractional
point. part).
Examples
-3,0,25, 1024, 15 3.14,-0.5,2.0,0.0, 18.70
Arithmetic results
Arithmetic results stay integers if all operands are Arithmetic can result in float even if one operand
integers is float
(3) Define operator precedence and give an example of an expression where operator precedence
affects the result.
Ans: 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 '()'
It has highest precedence. Operations inside parentheses are performed first. (3 + 2) * 4 evaluates to
20.
 Exponentiation Performs power operations next. 23 evaluates to 8.
UNIT– 2 6
0
 Multiplication '*', Division '/', and Modulus '%':
These operations come next. 4*3 evaluates to 12, 10/2 evaluates to 5.0 and 11%3 evaluates.
 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
Example 10+3*2**2-5/5
=21
(4) How does the short hand if-else statement differ from the regular if-else statement?
Ans: Following are the differences between short hand if-else statement and regular if-else statement:
SHORT HAND IF-ELSE STATEMENT IF-ELSE STATEMENT
Definition
Python also allows a short-hand if-else The if-else statement allows us to execute one block
statement that can be written in a single line. of code if a condition is true and another block if the
condition is false.
Syntax
#Syntax of short hand if-else statement # Syntax of if-else statement if condition:
Action if_true if condition else action_if_false If condition:
# code to run if the condition is true else :
else:
# code to run if the condition is false
Readability
It is cleaner for simple conditions. It is easier for complex logic.
Flexibility
It is only used for expressions/assignments. It Can multiple statements.
Example
temperature = 15
temperature = 15 if temperature > 30:
m = “It’s a hot day” if temperature > 30 print("It’s a hot day ")
else “It’s not a hot day” else :
print(m) print("It’s not a hot day " )

(5) Explain the use of the range() function in a for loop?


Ans: The range() function in Python is commonly used with for loops to generate a sequence of
numbers over which the loop can iterate. We can use the range() function to generate a sequence
of numbers, which is often used in for loops.
Syntax
# Syntax of range function
range(start, stop, step)
range(stop) range(start, stop) range(start, stop, step)
 start (optional): Starting number of the sequence (default is 0)
 stop End of the sequence (not included)
 step (optional): Difference between each number (default is 1)
Example
Print the numbers from 0 to 4. Output
Python code: 0
for i in range (5): 1
print (i) 2
Explanation 3
4
UNIT– 2 6
1
The above code generates numbers from 0 to 4 and prints each number.
(6) Explain how default parameters work in Python functions?
Ans: In Python, default parameters allow you to assign default values to function arguments. If a
value for that parameter is not provided when the function is called, the default is used.
Functions can have default parameter values, which are used if no argument is provided during the
function call.
Syntax
def function_name(param1, param2=default_value):
# function body
Example
Define a function with a default parameter.
def greet(name = "Student") :
return "As-Salaam-Alaikum,"+ name +"!"
print(greet( ))
# Output As-Salaam-Alaikum,Student!
print(greet("Umer "))
# Output As-Salaam-Alaikum,Umer!
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.
(7) Explain why modular programming is useful in Python.
Ans: Functions and modules in Python are key to writing efficient and organized code. 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 # [Link]
approach simplifies managing complex programs and def main () :
promotes code reuse. In Python, this typically means printC'This is the main function.")
dividing your code into functions, classes, and if name ==" main ":
[Link] files (modules). main()
Benefits of Modular in Python Programming:
 Improves Code Organization
 Enhances Reusability
 Simplifies Debugging and Testing
 Facilitates Collaboration
 Promotes Maintainability
 Encourages Abstraction
 Supports Python’s Built-in Module System
(8) Explain the difference between a class and an object in Python.
Ans: Following are the difference between a class and an object in Python.
CLASS OBJECT
Definition
A class is like a blueprint or template used for An object is an actual item created from a class
creating an object . (template).
Properties
A class is a design of car. You first need a An object is the actual toy car. Each object is a
blueprint or a template that describes how the toy unique instance of the class, meaning it uses the
car should look and function. class as a plan.
Example

UNIT– 2 6
2
The “ToyCar” class is like the template for “carl” and “car2” are specific toy cars created
making toy cars. It describes what attributes a toy using the ToyCar [Link] has its own unique
car should have: color, size, and wheels. attributes.

Entity
Class is a Logical entity in a python language. Object is a physical entity in python Language.
Memory
No memory allocated upon declaration of class Memory is allocated when object is created in
in python. python.
Time
Class declared once in a python. Object can be created multiple times in python.
TEXT BOOK LONG QUESTIONS
(1) Evaluate the following Python expressions.
(a) (18 / 3 +4 ** 2) - (2 * (7 - 3)) /(97- 4)
(b) (25 + 3 * 4 ** 2 - 6) / (2 ** 3 + 1)- 7
(c) (12 + 6 *(5-2)) ** 2 / ((4 ** 2 - 7) + 10)
(d) 45 / (2 ** 2 + 3 *4) + 8 * (7 - 3)
SOLUTIONS
(a) (18 / 3 +4 ** 2) - (2 * (7 - 3)) /(97-4)
SOLUTION (A)
Step 1: Exponentiation
4 ** 2 = 16
Step 2: Division
18 / 3 = 6.0
Step 3: Addition
6.0 + 16 = 22.0
Step 4: Parentheses (subtraction)
7-3=4
Step 5: Multiplication
2*4=8
Step 6: Add the denominator
97 - 4 = 93
Step 7: Division
8 / 93 = 0.0860215
Step 8: Final subtraction
22.0 - 0.0860215 = 21.9139785
(b) (25 + 3 * 4 ** 2 - 6) / (2 ** 3 + 1)- 7
SOLUTION (B)
Step-by-step Breakdown:
Step 1: Exponentiation
4 ** 2 = 16
2 ** 3 = 8
Step 2: Multiplication
3 * 16 = 48
Step 3: Evaluate numerator
25 + 48 - 6 = 67
Step 4: Evaluate denominator
8+1=9
Step 5: Division
67 / 9 = 7.4444

UNIT– 2 6
3
Step 6: Subtraction
7.4444 - 7 = 0.4444
(c) (12 + 6 *(5-2)) ** 2 / ((4 ** 2 - 7) + 10)
SOLUTION (C)
Step-by-Step Evaluation
Step 1: Parentheses inside
(5 - 2) = 3
6 * 3 = 18
12 + 18 = 30
Now the numerator becomes:
30 ** 2 = 900
Step 2: Denominator
4 ** 2 = 16
16 - 7 = 9
9 + 10 = 19
Step 3: Final Division
900 / 19 = 47.3684
(d) 45 / (2 ** 2 + 3 *4) + 8 * (7 - 3)
SOLUTION (D)
Step-by-Step Evaluation
Step 1: Exponentiation
2 ** 2 = 4
Step 2: Multiplication
3 * 4 = 12
Step 3: Denominator of division
4 + 12 = 16
Step 4: First part of the expression
45 / 16 = 2.8125
Step 5: Parentheses and multiplication
(7 - 3) = 4
8 * 4 = 32
Step 6: Final addition
1.8125 + 32 = 34.8125
(2) Translating the following Mathematical Expressions to Python Syntax
(a) 5 × (3 + 22) × 6-2 ×3
(b) 7 + 22
SOLUTIONS
SOLUTION:(A)
(a) Given:
5 × (3 + 2²) × 6 − 2 × 3
Step-by-step breakdown:
 2² → In Python: 2**2
 3 + 2² → In Python: 3 + 2**2
 Multiply that sum by 5 → 5 * (3 + 2**2)
 Multiply the result by 6
 Subtract 2 * 3
Given:
Python syntax
= 5 * (3 + 2**2) * 6 - 2 * 3 = 204
SOLUTION:(B)

UNIT– 2 6
4
(b) Given:
7+22
Python syntax
= 7 + 2**2
This evaluates to 7 + 4 = 11.
(3) Explain the concept of variables in Python.
Ans: VARIABLE
A variable is a storage container in a computer's memory, that allows storage, retrieval an
manipulation of data.
The value of a variable can change throughout the execution of a program.

age = 71
print( "Ahmad lived for", age, "years")
age = 60
print ( "Iqbal lived for", age, "years")
VARIABLE NAMING RULES IN PYTHON
Variable names in Python must adhere to the following rules:
 The name must begin with a letter (a-z, A-Z) or an underscore (_).
 Subsequent characters can include letters, digits (0-9), or underscores ( _ ).
 Variable names are case-sensitive, meaning age and Age are considered two different
variables.
 Python's reserved keywords, such as for, while, if, etc., cannot be used as variable names.
(4) Write a Python program that takes a number as input and checks whether it is positive,
negative, or zero using an if-elif-else statement.
Ans: This program takes a number from the user and checks three conditions:
number = int(input("Enter a number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")

Outputs:
Enter a number: 5
Positive

(5) Write a Python program using a while loop that prints all the odd numbers between 1 and
100. Also, count and print the total number of odd numbers.
Ans: This program uses a while loop to print odd numbers and count them:
# Define the limit
Output:
Enter the upper limit: 100
UNIT– 2 6
1
5
3
5
7
limit = 100
i=1
odd_count = 0
while i <= limit:
if i % 2 != 0:
print(i)
odd_count += 1
i += 1

SELF IMPROVEMENT TEST (SIT)


Total Time: 40 Minutes Total Marks = 30

Q.1 Encircle the Correct Answer from the Multiple Choices: (6 × 1 = 6)


(i) Which is a popular, versatile language known for its simplicity and readability, making it
ideal for both beginners and professionals?
(A) B language (B) C language
(C) C++ language (D) Python language
(ii) Which function is used to convert user input into an integer in Python?
(A) float() (B) str()
(C) int() (D) input()
(iii) Which of the following operators is used to multiply and assign in one step?
(A) *= (B) **=
(C) x= (D) /*
(iv) What type of loop is best used when the number of iterations is unknown beforehand?
(A) for loop (B) do-while loop
(C) while loop (D) range loop
(v) Which keyword is used to define a function in Python?
(A) def (B) include
(C) define (D) function
(vi) Which operation is used to combine two lists in Python?
(A) * (B) &
(C) + (D) combine()

Q.2 Write Short Answers. (4 × 2 = 8)


(i) Explain the difference between a class and an object in python.
(ii) How do you display output to the user in Python?
(iii) What does the != operator do in Python?
(iv) What is the main difference between a for loop and a while loop in Python?

Q.3 Write Long Answers. (2 × 8 = 16)


(i) Scenario:
Sarah is developing a simple budgeting app in Python to help users manage their expenses. She
defines two variables: income = 5000 and expenses = 3200. She wants to calculate the remaining
balance after expenses, determine if the savings target of $1500 is met, and then adjust her future
savings target based on whether she exceeded or fell short of it.

UNIT– 2 6
6
Question:
Write a suitable python code that design an application of above given data.
(ii) Discuss the use of a for loop in iterating through a list of students and checking if any student has
failed (assume pass mark is 40). Demonstrate how decision making and looping are used together
in this context.

SELF IMPROVEMENT TEST (SIT)

1 D 2 C 3 A
4 C 5 A 6 C

UNIT– 2 6
7

You might also like