Inter 1 Computer Unit 2 Notes
Inter 1 Computer Unit 2 Notes
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.
Work with Python modules, functions, and built-in data structures like lists.
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.
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.
Always use meaningful names for variables to make your code easier to
understand. For example, use age instead of a.
(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.
# 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)
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.
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.
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)
(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.")
UNIT– 2 4
4
You can call a function multiple times with different arguments to reuse
the same code for different inputs.
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"]
# 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.
EXTENSIVE QUESTIONS
(1) Discuss how Python’s functions, modules, and libraries contribute to writing efficient and
maintainable programs.
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
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.
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"
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.
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.
(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 " )
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
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.
1 D 2 C 3 A
4 C 5 A 6 C
UNIT– 2 6
7