Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
EXERCISE
Q 1. Select the best answer for the following Multiple-Choice Questions (MCQs.
1. Computer Programs are categorized into:
a) Interactive Program and Batch Program b) Inactive Program and Badge Program
c) Inactive Program and Batch Program d) Inactive Program and Badge Program
2. Python was first introduced in
a) 1990 b) 1994 c) 1992 d) 2022
3. Operator != is used for _____.
a) Equal b) Logical AND c) Not equal d) Logical OR
4. We can design 2D geometrical shapes in Python, using _____.
a) Operators b) Iterations c) Variables d) Turtle Graphics
5. What will the following program do
for i in range(10,0,-1)
print(‘iteration no-‘, i)
a) it will give an error b) it will run 9 times
c) it will run 10 times d) it will run 11 times
6. The interactive computer program accepts some input which is from a user program
like:
a) Sub program b) Web browser c) Print job d) Page break
7. _____ provide basic variable types as str, integer, float, etc.
a) Print job b) Page break c) Python d) Procedure
8. The input() function treats the entered data as a set of
a) Digits b) Characters c) Symbols d) Arithmetic operators
9. Python provide the option of Modulo operator represented as _____.
a) = b) == c) ! d) %
10. ‘**’ is used to represent _____.
a) Division b) by Floor division c) Multiplication d) Exponentiation
11. If the program is unable to execute the next instruction, the program will reach the state
of _____.
a) Hang b) Reboot c) Shutdown d) Sleep
12. We apply comparison with the help of _____ statement.
a) For b) While c) If d) But
13. In online IDEs, we can write and run our code without _____ in our computer.
a) Installing b) Creating c) Performing d) Detecting
14. IDE stands for _____.
a) Internet Development Environment b) Illegal Development Environment
c) Integrated Development Environment d) installer Development Environment
(IDLE stands for Integrated Development and Learning Environment)
15. Turtle graphics help us to design basic drawing and _____.
a) 1D shapes b) 2D shapes c) 3D shapes d) 40 shapes
16. A REPL means _____.
a) Read-Enter-Print-Loop b) Read-Exit-Print-Loop
c) Read-Eval-Print-Loop d) Read Evolve-Print-Loop
17. To draw a triangle, we need to play with _____.
a) Angles b) Vertices c) Lines d) Shapes
18. Bug is an unanticipated error which is generally _____ in nature.
a) Analog b) Digital c) Logical d) Legal
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 1 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q 1. What are the applications of computer programming in daily life?
Ans. Computer programming plays a significant role in many aspects of daily life, like:
• WhatsApp, Instagram, Facebook, and Zoom rely on programming for functionality.
• Google Maps use programming to calculate routes, estimate travel times, and
provide real-time traffic updates.
• Online Banking use programming to supports secure transactions, account
management, and loan applications.
Q. What is computer program? How is a program executed?
• A set of well-defined instructions that can be executed by a computer to solve a problem is
called computer program.
Program Execution
• The program is loaded from disk memory into main memory (RAM) for CPU to execute it.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 2 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. What are general categories of computer programs?
1. Interactive Programs
• An Interactive program is a program that requires real-time input from a user to work.
• The program responds to the commands as they are provided.
Example:
• A web browser is an interactive program as it waits for user actions such as clicking or
double clicking to load pages or submit forms etc.
• The calculator app is an interactive program as it requires user input such as entenng
numbers and pressing buttons like or to perform calculation and show the result.
2. Batch Programs
• A batch program executes a series of pre-defined commands or tasks without user
interaction aung execution.
• These programs are desigried to execute commands automatically in a sequence.
• They are useful to perform the tasks that need to be repeated regularly.
Example
• The print jobs on a printer line up in a queue and are processed one by one without
requiring user interaction. The process stops when no more jobs are in the queue.
• The programs that automatically coples files from one location to another af scheduled
time such as daily backups of important documents to an external hard drive.
Machine Language Assembly Language High Level Language
• It is in binary format (0, 1). • It uses codes called • It uses English like
• It is difficult for human to Mnemonics. statements.
understand. • It uses Assembler as a • It is easy to write, debug
• No translator is required, translator. and modify.
computer can directly • It is easier than machine • Compiler and interpreters
understand it. language. are used as translator.
Assembler Compiler Interpreter
• A type of translator used to • A type of translator used to • A type of translator used to
translate Assembly translate High Level translate High Level
language (Mnemonics) Language, the whole Language, one statement
into machine code. program at once into at a time into machine
machine code. code.
Source Code Object Code Executable Code
• A program/ code written in • A translated program/code • A program/ code executed
any high-level language. by the compiler into by the CPU.
• It is in English like machine code. • It is in machine code
statements. • It is in machine code but format.
cannot be executed.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 3 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. List down the languages that uses compiler and interpreter.
Compiler Interpreter
i. C/C++ i. Python
ii. Java ii. JavaScript
iii. Assembly iii. Ruby
iv. Fortran etc. iv. PHP etc.
Q. Write down the application areas of Python.
i. Data Analysis
ii. Machine Learning
iii. Software Development/ App. Development
v. Website Development
vi. Artificial Intelligence etc.
Q. Why Python is popular?
i. A great starting point for individuals who are unfamiliar with programming.
ii. Easy to write, debug and modify. Its syntax is quite similar to that of English.
iii. An open-source programming language, meaning any body can use it and help is
available on different sites and platforms, as developers around the world share
their experiences.
Q. Why Python is excellent for web development?
Python is excellent for web development, mainly because there are several Python web
development frameworks available like:
i. Django
ii. Pyramid
iii. Flask
Framework is an IDE where multiple languages code can be used.
Python IDE can be downloaded as IDLE from hppts://www.python.org/downloads
Q. What is a Replit?
i. It is an online IDE available through which you can write and run your code, without
installing it on your computer.
ii. It provides attractive console and easy to use environment, which are feasible for
small block of codes, especially for beginners.
iii. Create a REPL (Read-Eval-Print-Loop) by pressing the ‘Create Repl’ button.
Replit is the name of the website and REPL (Read-Eval-Print-Loop) is the name of the folder.
Q. List the names of online Python IDEs?
i. https://onecompiler.com/python
ii. https://www.online-python.com/
iii. https://www.onlinegdb.com/online_python_compiler
iv. https://www.programiz.com/python-programming/online-compiler/
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 4 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. What are Turtle Graphics?
i. Turtle graphics is pre-installed with Python, and we have just to invoke it and use it.
ii. It provides functions which can be easily used even from the shell prompt.
iii. Through these functions we can design basic drawings and two-dimensional
geometrical shapes.
iv. Turtle provides advanced features which are quite useful for the development of
animations, simulations and computer games.
The “import turtle“ command is used to invoke the turtle library and all the functions can
now be used.
Q. What is a circle method in Python?
• The circle() method is used to draw a circle of a specified radius.
Syntax:
turtle.circle(radius, extent=Optional, steps=Optional)
• radius: If the radius is positive, the circle is drawn in a counter-clockwise direction.
If negative, it is drawn clockwise.
• extent: The extent of the arc in degrees (if not provided, it draws a full circle).
• steps: The higher the steps, the smoother the circle.
Q. Write a program to create a circle.
import turtle
turtle.circle(100)
import turtle
turtle.circle(100)
turtle.circle(-100)
import turtle
turtle.circle(100)
turtle.circle(-100,90)
import turtle
turtle.circle(100)
turtle.circle(-100,180)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 5 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
import turtle
turtle.circle(100)
turtle.circle(-100,360,10)
import turtle
turtle.circle(100)
turtle.circle(-100,360,100)
Q. Write a program to draw 10 coinciding circles.
import turtle
for r in range(10, 100, 10):
turtle.circle(r)
Q. Write a program to draw concentric circles.
import turtle
r = 10
for i in range(10):
turtle.circle(r*i)
turtle.up()
turtle.sety((r*i)*(-1))
turtle.down()
Q. Write a program to draw spiral circle.
import turtle
r = 10
for i in range(100):
turtle.circle(r+i, 45)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 6 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. What is a screen function in Python?
• In the turtle library, Screen is a class that represents the window where the turtle
graphics appear.
• To create a Screen object, you can use the Screen() method.
turtle.screen()
Q. Write a program that can handle screen in Python.
import turtle
screen = turtle.Screen()
screen.title("My Turtle Graphics")
screen.bgcolor("lightblue")
screen.exitonclick()
Q. Write a program that can create an EQUILATERAL triangle in Python.
import turtle
screen = turtle.Screen()
screen.title("My Turtle Graphics")
screen.bgcolor("lightblue")
turtle.forward(140)
turtle.left(135)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
screen.exitonclick()
Q. Write a program that can create an EQUILATERAL triangle with red color in Python.
import turtle
screen = turtle.Screen()
screen.title("My Turtle Graphics")
screen.bgcolor("lightblue")
turtle.dot(10, "Red")
turtle.pencolor("Red")
turtle.forward(140)
turtle.left(135)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
screen.exitonclick()
Q. Write a program that can create an EQUILATERAL triangle using loop in Python.
import turtle
for _ in range(3):
turtle.forward(100)
turtle.left(120)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 7 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can create RIGHT-ANGLE triangle using loop in Python.
import turtle
turtle.forward(100) # Base
turtle.left(90)
turtle.forward(100) # Perpendicular
turtle.left(135)
turtle.forward(141) # Hypotenuse (approx.)
Q. Write a program that can create an ISOSCELES triangle using loop in Python.
import turtle
turtle.forward(100) # First equal side
turtle.left(60)
turtle.forward(100) # Second equal side
turtle.left(150)
turtle.forward(173) # Base (approx.)
Method Parameter Description
Turtle() None Creates and returns a new turtle object
forward() amount Moves the turtle forward by the specified amount
backward() amount Moves the turtle backward by the specified amount
right() angle Turns the turtle clockwise
left() angle Turns the turtle counterclockwise
penup() None Picks up the turtle’s Pen
pendown() None Puts down the turtle’s Pen
up() None Picks up the turtle’s Pen
down() None Puts down the turtle’s Pen
color() Color name Changes the color of the turtle’s pen
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
heading() None Returns the current heading
position() None Returns the current position
goto() x, y Move the turtle to position x,y
begin_fill() None Remember the starting point for a filled polygon
end_fill() None Close the polygon and fill with the current fill color
dot() None Leave the dot at the current position
stamp() None Leaves an impression of a turtle shape at the current location
shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 8 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. How to control the position of graphics on screen in Python?
• The screen is divided into four quadrants.
• The initial position of the turtle is (0,0), called Home.
• To move the turtle to any other area on the screen goto() method is used.
Q. Write a program to create a sketch of a car.
import turtle turtle.goto(130,-100)
turtle.pencolor("Blue") turtle.pendown()
turtle.begin_fill() turtle.circle(20)
turtle.fillcolor("Blue") turtle.penup()
turtle.forward(200) turtle.goto(50,-100)
turtle.right(90) turtle.pendown()
turtle.forward(80) turtle.dot(20,"Green")
turtle.right(90) turtle.penup()
turtle.forward(200) turtle.goto(150,-100)
turtle.right(90) turtle.pendown()
turtle.forward(80) turtle.dot(20,"Green")
turtle.end_fill() Output
turtle.goto(30,0)
turtle.pencolor("Red")
turtle.begin_fill()
turtle.fillcolor("Red")
turtle.circle(-70,180)
turtle.end_fill()
turtle.penup()
turtle.goto(30,-100)
turtle.pendown()
turtle.pencolor("Green")
turtle.circle(20)
turtle.penup()
Q. What is a library in Python? How to use additional library?.
• A set of code which used for a particular task more proficient, is called library.
• Turtle library is already available in Python, provides functions that we can use.
• For additional library, it can be downloaded and imported similarly.
• The pip (Preferred Installer Program) is a command-line utility that installs,
reinstalls and uninstalls packages.
• > pip install datetime
Q. How to use now() method with datetime library in Python?
import datetime Output
x = datetime.datetime.now() 2024 – 10 – 16 21:28 :26 . 528349
print(x) Year – Month – Day Hr : Min:Sec . Microsecond
import datetime
x = datetime.datetime.now() Output
print(x.day) 19
print(x.month) 10
print(x.year) 2024
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 9 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Define strftime() methods in Python?
• The strftime() method in Python is used to format date and time objects into
readable strings.
• It stands for "string format time" and is part of the datetime module.
• With strftime(), you can specify a format string to control how the date and time
should be represented.
Syntax: strftime(format)
Q. How to use strftime() methods in Python?
import datetime Output
x = datetime.datetime.now() October
print(x.strftime("%B"))
import datetime Output
x = datetime.datetime.now() 2024
print(x.year) Wednesday
print(x.strftime("%A"))
import datetime Output
x = datetime.datetime.now() Day = 19
print("Day = ",x.day) Month = 10
print("Month = ",x.month) Year = 2024
print("Year = ",x.year)
Q. List down the arguments available for use in datetime library for strftime() method.
Argument Description Example
%A Weekday, full version Friday
%B Month name, full version August
%C Century 24
%D Day of the month 01-31 21
%H Hour 00-23 18
%I Hour 00-12 03
%S Second 00-59 48
%Y Year, full version 2024
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 10 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Insall pygame library using pip and creating a BOUNCING BALL program.
import pygame
# Initialize pygame
pygame.init()
# Set up the game window
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball")
# Colors
black = (0, 0, 0)
red = (255, 0, 0)
# Ball properties
ball_radius = 20
ball_x = width // 2
ball_y = height // 2
ball_speed_x = 5
ball_speed_y = 5
# Game loop
running = True
while running:
screen.fill(black)
# Check for events (like closing the window)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move the ball
ball_x += ball_speed_x
ball_y += ball_speed_y
# Bounce the ball off the walls
if ball_x - ball_radius < 0 or ball_x + ball_radius > width:
ball_speed_x = -ball_speed_x
if ball_y - ball_radius < 0 or ball_y + ball_radius > height:
ball_speed_y = -ball_speed_y
# Draw the ball
pygame.draw.circle(screen, red, (ball_x, ball_y), ball_radius)
# Refresh the screen
pygame.display.flip()
# Set the frame rate
pygame.time.Clock().tick(60)
# Quit pygame
pygame.quit()
Q. What are variables?
• A variable is a named memory location.
• It is used to store the program’s input data and its computational results during
execution of a program.
• The value of a variable may change during the execution of a program.
Example: Length, _Sum, Num1 etc.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 11 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write down variable naming rule.
i. The characters allowed in variable names are alphabets (a-z, A-Z), numbers (0-9)
and underscore (_).
ii. Cannot start with a number.
iii. Cannot contain spaces.
iv. Cannot contain special symbols.
v. Python is a case-sensitive language. Variable LENGTH is different from length.
Bugs are the errors in a computer program and debugging is the process of removing of
errors.
Syntax Error Logical Error Execution Error
• An error in code that • An error where the • An error occurs when a
violates the programming instructions given in the program is asked to do
language's rules. program do not accomplish something that it cannot,
• For example, writing the intended goal. resulting in a 'crash'.
Print() instead of print() is • For example, writing • For example, division of a
a syntax error. formula area of rectangle number by zero.
length + width instead of
length * width
Q. How input works in Python? Write about input() function.
• The function input() is used to get input from user at runtime.
• Num = input(“Enter an Integer”)
• The string will be displayed on screen and ask user to enter a value.
• The input() function treats the entered data as set of characters, if numeral is
entered , it needs to be converted into number.
Q. How output works in Python? Write about print() function.
• The function print() is used to give output in Python.
• print(“Welcome”)
• The message within the parentheses is a string and it will be displayed
Q. Define the int() function.
• With int() the input is treated as integer.
• N = int(input(“Enter an Integer”))
• Numeral entered by input() function, needs to be converted to integer using int().
Q. Define the float() function.
• With float() the input is treated as number with decimal point.
• N = float(input(“Enter an Integer”))
• Numeral entered by input() function, needs to be converted to number with
decimal point.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 12 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program to assign two numbers Q. Write a program that can accept two
and print their sum. numbers from user and print their sum.
A=5 A = int(input(“Enter an integer “))
B = 10 B = int(input(“Enter an integer “))
Sum = A + B Sum = A + B
print(“Sum = “, Sum) print(“Sum = “, Sum)
Q. Correct the following Python code segments by removing errors: (Model Paper Q 2. i)
Incorrect Code Code without errors
num1 = 10 num1 = 10
num2 = “5” num2 = 5
result = num1 + num2 result = num1 + num2
print(result) print(result)
fruits = [“Islamabad”, “Karachi”, “Lahore”] fruits = [“Islamabad”, “Karachi”, “Lahore”]
print(fruits[3]) print(fruits[2])
num1 = 10 num1 = 10
num2 = 0 num2 = 5
result = num1 / num2 result = num1 / num2
print(result) print(result)
Q. Write a program that can accept length Q. Write a program that can accept length
and width for a rectangle and calculate it’s and width for a rectangle and calculate it’s
area. perimeter.
Length = float(input(“Enter Length “)) Length = float(input(“Enter Length “))
Width = float(input(“Enter Width “)) Width = float(input(“Enter Width “))
Area = Length * Width Peri = 2 * (Length + Width)
print(“Area of Rectangle = “, Area) print(“Perimeter of Rectangle = “, Peri)
Q. Write a program that can accept radius Q. Write a program that can accept radius
for a Circle and calculate it’s area. for a Circle and calculate it’s circumference.
Radius = float(input(“Enter Radius “)) Radius = float(input(“Enter Radius “))
Area = 3.1412 * Radius * Radius Circum = 2 * 3.1412 * Radius
print(“Area of Circle = “, Area) print(“Circumference of Circle = “, Circum)
Q. Write a program that can accept base Q. Write a program that can accept three
and height for a Triangle and calculate area. sides of a Triangle and calculate perimeter.
Base = float(input(“Enter Base “)) SideA = float(input(“Enter Side A “))
Height = float(input(“Enter Height “)) SideB = float(input(“Enter Side B “))
Area = 0.5 *(Base * Height) SideC = float(input(“Enter Side CA “))
print(“Area of Triangle = “, Area) Peri = SideA + SideB + SideC
print(“Perimeter of Triangle = “, Peri)
Q. Write a program that can accept Q. Write a program that can accept
temperature in Fahrenheit and convert it temperature in centigrade and convert it
into centigrade. into Fahrenheit.
Fah = float(input(“Enter temperature “)) Cent = float(input(“Enter temperature “))
Cent = 5/9 *(Fah – 32) Fah = 9/5 * Cent + 32
print(“Temperature in Centigrade = “, Cent) print(“Temperature in Fahrenheit = “, Fah)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 13 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can accept two numbers and swap their values.
A = int(input(“Enter an integer in A “))
B = int(input(“Enter an integer in B “))
Temp = A
A=B
B = Temp
print(“Swapped Values A = “, A, “ B = “, B)
Q. Write a program that can accept two numbers and swap their values without using
third variable. (Activity 1, Page # 105)
A = int(input(“Enter an integer in A “))
B = int(input(“Enter an integer in B “))
A=A+B
B=A–B
A=A–B
print(“Swapped Values A = “, A, “ B = “, B)
Q. Write a program that can accept bank Q. Write a program that can accept
balance and calculate interest @ 7%. obtained marks and total marks and
calculate percentage of marks.
Balance = int(input(“Enter bank balance “)) OM = int(input(“Enter obtained marks “))
Interest = Balance / 100* 7 TM = int(input(“Enter total marks “))
print(“Amount of interest = “, Interest) Percentage = OM/TM * 100
print(“Percentage of marks = “, Percentage)
Q. How eval() function works?
• With eval() the input is treated as number.
• N = eval(input(“Enter an Integer”))
• Numeral entered by input() function, needs to be converted to number using eval().
Q. What will be the output of the following code?
Source Code Output
Num = input(“Enter a number: ”) Enter a number: 123
print(“Double of number is “, Num + Num) Double of number is 123123
Num = eval(input(“Enter a number ”)) Enter a number: 123
print(“Double of number is “, Num + Num) Double of number is 246
Q. Take three inputs as day, month, and year, i.e. your date of birth, store them in three
variables and print in the form of: 13-10-2024
10-13-2024
2024-10-13 (Activity 2, Page # 107)
day = input("Enter day (DD): ") Output
month = input("Enter month (MM): ") Enter day (DD): 2
year = input("Enter year (YYYY): ") Enter month (MM): 12
print(day, "-", month, "-", year) Enter year (YYYY): 2024
print(month, "-", day, "-", year) 2 - 12 - 2024
print(year, "-", month, "-", day) 12 - 2 - 2024
2024 - 12 - 2
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 14 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write about the working of arithmetic operators.
Operator Name Example Result
+ Addition 5+2 7
– Subtraction 5–2 3
* Multiplication 5*2 10
/ Division 5/2 2.5
// Floor Division 5 // 2 2
% Modulus 5%2 1
** Exponentiation 5 ** 2 25
Q. Write down the precedence order of arithmetic operators.
Order Name Symbol
1st Parentheses ()
2nd Exponent **
3 rd Multiplication and Division *, /, //, %
4 th Addition and Subtraction +, -
Associativity of arithmetic operators: Operators that have the same precedence are
evaluated from left to right.
Q. Write about the working of arithmetic assignment operators.
Operator Example Equivalent
+= A += 2 A=A+2
–= B –= 2 B=B–2
*= C *= 2 C = C *2
/= D /= 2 D=D/2
//= E //= 2 E = E // 2
%= F %= 2 F=F%2
**= G **= 2 G = G ** 2
Q. Write a program that can accept numbers of apples and number of children. Calculate
how many apples each child has and how many are left behind.
Note:- Number of apples should be greater than number of children.
Apple = eval(input("Enter number of apples: "))
Child = eval(input("Enter number of children: "))
print("Number of apple each child get: ", Apple//Child)
print("Number of apple left behind ", Apple % Child)
Q. Write a program that can accept length of plastic paper sheet, and number of students.
Divide sheet equally into students.
Length = int(input(“Enter length of plastic paper sheet in meters ”))
Students = int(input(“Enter number of students “))
print("Each student get plastic paper sheet “, Sheet/Student, “meters “)
Q. Write a program that can accept a number and print its square.
Num = int(input(“Enter an integer ”))
print("Square of the number is “, Num ** 2)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 15 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Describe bitwise operators used in Python.
Bitwise operators in Python perform operations on the binary representations of integers.
1. Bitwise AND (&) Compares each bit of two integers; returns 1 if both bits are 1.
a = 12 # In binary: 1100
b=5 # In binary: 0101
result = a & b # Result: 4 (In binary: 0100)
print(result) # Output: 4
2. Bitwise OR (|) Compares each bit of two integers; returns 1 if at least one bit is 1.
a = 12 # In binary: 1100
b=5 # In binary: 0101
result = a | b # Result: 13 (In binary: 1101)
print(result) # Output: 13
3. Bitwise XOR (^) Compares each bit of two integers; returns 1 if the bits are different.
a = 12 # In binary: 1100
b=5 # In binary: 0101
result = a ^ b # Result: 9 (In binary: 1001)
print(result) # Output: 9
4. Bitwise NOT (~) Inverts all bits of the integer.
a = 12 # In binary: 1100
result = ~a # Result: -13
# (In binary: ...11110011 in 2's complement)
print(result) # Output: -13
5. Left Shift (<<) Shifts bits to the left, filling with zeros. This effectively multiplies the
number by 2 for each shift.
a=3 # In binary: 0011
result = a << 2 # Result: 12 (In binary: 1100)
print(result) # Output: 12
6. Right Shift (>>) Shifts bits to the right. This effectively divides the number by 2 for
each shift.
a = 12 # In binary: 1100
result = a >> 2 # Result: 3 (In binary: 0011)
print(result) # Output: 3
Q. Describe Membership operators used in Python.
Bitwise operators in Python perform operations on the binary representations of integers.
1. In Returns True if the specified value is found in the sequence.
Syntax: value in sequence
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
2. not in Returns True if the specified value is not found in the sequence.
Syntax: value not in sequence
fruits = ["apple", "banana", "cherry"]
print("mango" not in fruits) # True
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 16 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Describe Comparison operators used in Python.
Bitwise operators in Python perform operations on the binary representations of integers.
1. Equal to (==) Checks if two values are equal.
a = 5; b = 5; print(a == b) # True
2. Not equal to Checks if two values are not equal.
(!=) a = 5; b = 3; print(a != b) # True
3. Greater than (>) Checks if the left value is greater than the right value.
a = 7; b = 5; print(a > b) # True
4. Less than (<) Checks if the left value is less than the right value.
a = 3; b = 5; print(a < b) # True
5. Greater than or Checks if the left value is greater than or equal to the right value.
equal to (>=) a = 5; b = 5; print(a >= b) # True
6. Less than or Checks if the left value is less than or equal to the right value.
equal to (<=) a = 3; b = 5; print(a <= b) # True
Q. Describe Logical operators used in Python.
• Logical operators are used to combine conditional statements.
• These operators return a Boolean value (True or False).
• They are commonly used in control flow statements like if, while, and for.
1. Logical AND Returns True if both operands are true.
(and) Syntax: condition1 and condition2
a = 5; b = 10
print(a > 0 and b > 0) # True (Both conditions are true)
print(a > 0 and b < 0) # False (Second condition is false)
2. Logical OR (or) Returns True if at least one operand is true.
Syntax: condition1 or condition2
a = 5; b = -10
print(a > 0 or b > 0) # True (First condition is true)
print(a < 0 or b < 0) # True (Second condition is true)
3. Logical NOT Returns True if the operand is false. It inverts the Boolean value.
(not) Syntax: not condition
a = True
print(not a) # False (Inverts the value of a)
print(not (5 > 10)) # True (Inverts the false condition)
Q. What are membership operators?
• Membership operators in Python are used to check whether a specified value exists
in an object or not.
• The operators are ‘in’ and ‘not in’.
• They return true if a value is present and not present respectively.
1. in • Returns True if the value is present in the object.
• Returns False if the value is not present in the object.
Syntax: value in sequence
List = [ 1, 3, 5, 7 ]
print( 5 in List ) # Output: True
print( 9 in List ) # Output: False
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 17 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
2. not in • Returns True if the value is not present in the object.
• Returns False if the value is present in the object.
Syntax: value not in sequence
List = [ 1, 3, 5, 7 ]
print( 5 not in List ) # Output: False
print( 9 not in List ) # Output: True
Q. Describe if statement used in Python.
• The if statement is used for conditional execution.
• It allows the program to execute a block of code only if a specified condition is True.
Syntax:
if condition:
# code to execute if the condition is True
x = 10
if x > 5:
print("x is greater than 5") # the output will be x is greater than 5
Q. Describe if else statement used in Python.
• The if else statement is used for conditional execution.
• It allows the program to execute a block of code if a specified condition is True
otherwise execute another block of code. The basic syntax of an if statement is:
Syntax:
if condition:
# code to execute if the condition is True
else:
# code to execute if the condition is False
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Q. Describe if elif else statement used in Python.
• The if elif else statement is used for multiple conditional execution.
• It allows the program to execute a block of code if a specified condition is True
otherwise it will check for other condition.
• If none of the condition is true the block of code after else will be executed.
Syntax:
if condition-1:
# code to execute if the condition-1 is True
elif condition-2:
# code to execute if the condition-2 is True
-
-
elif condtion n:
# code to execute if the condition-n is True
else:
# code to execute if all conditions are False
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 18 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
age = 17
if age >= 18:
print("You are eligible to vote.")
elif age == 17:
print("You can pre-register to vote.")
else:
print("You are not eligible to vote.")
Q. Write about the importance of indentation rules in Python.
• Indentation is used to define blocks of code, such as those for loops, functions,
conditionals, and classes.
• Python requires consistent indentation throughout the same block.
• Mixing spaces and tabs for indentation can lead to errors.
• The standard style guide for Python (PEP 8) recommends using 4 spaces per
indentation level.
if True:
print("This is inside the if block")
for i in range(3):
print(i)
Q. Write a program that can accept a marks and check if he is pass(40%) or fail.
Marks = int(input(“Enter marks between 0 to 100: “))
if Marks >= 40:
print("Congratulations you are pass. ")
else:
print(“Try again.”)
Q. Write a program that can accept a number and check it is even or odd.
Num = int(input("Enter an integer: "))
if Num%2 == 0:
print("The number is EVEN ")
else:
print("The number is ODD")
Q. Write a program that can accept a number and check if it is positive, negative or zero.
Num = int(input("Enter an integer: "))
if Num > 0:
print("The number is POSITIVE ")
elif Num < 0:
print("The number is NEGATIVE")
else:
print("The number is ZERO ")
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 19 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can accept a week day number and print the name of week day.
Num = int(input("Enter week-day number: "))
if Num == 1:
print("Monday")
elif Num == 2:
print("Tuesday")
elif Num == 3:
print("Wednesday")
elif Num == 4:
print("Thursday")
elif Num == 5:
print("Friday")
elif Num == 6:
print("Saturday")
elif Num == 7:
print("Sunday")
else:
print("Invalid number ")
Q. Write a program that can accept a letter and check if it is a vowel or consonant.
Letter = input("Enter a letter: ")
if Letter == 'a' or Letter == 'A':
print("Vowel")
elif Letter == 'e' or Letter == 'E':
print("Vowel")
elif Letter == 'i' or Letter == 'I':
print("Vowel")
elif Letter == 'o' or Letter == 'O':
print("Vowel")
elif Letter == 'u' or Letter == 'U':
print("Vowel")
else:
print("A consonant ")
Q. Write a program that can accept marks and print their letter grades.
Marks = int(input("Enter marks: "))
if Marks >= 90:
print("A+")
elif Marks >= 80 and Marks <= 89:
print("A")
elif Marks >= 70 and Marks <= 79:
print("B")
elif Marks >= 60 and Marks <= 69:
print("C")
elif Marks >= 50 and Marks <= 59:
print("D")
else:
print("Unsatisfactory ")
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 20 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can accept three integers and print roots of quadratic equation.
import cmath
a = int(input("Enter integer a: "))
b = int(input("Enter integer b: "))
c = int(input("Enter integer c: "))
disc = b*b - 4*a*c
if disc > 0:
print("Root-1= ", (-b+cmath.sqrt(disc))/(2*a))
print("Root-2= ", (-b-cmath.sqrt(disc))/(2*a))
elif disc == 0:
print("Root= ", (-b/(2*a)))
else:
print("No real root exist ")
Q. Write a program that can accept three integers and print smallest among them.
a = int(input("Enter integer a: ")) Output
b = int(input("Enter integer b: ")) Enter integer a: 5
c = int(input("Enter integer c: ")) Enter integer b: 6
smallest = min(a,b,c) Enter integer c: 7
print("Smallest = ", smallest) Smallest = 5
Q. Write a program that can accept three integers and print largest among them.
a = int(input("Enter integer a: ")) Output
b = int(input("Enter integer b: ")) Enter integer a: 5
c = int(input("Enter integer c: ")) Enter integer b: 6
largest = max(a,b,c) Enter integer c: 7
print("Largest = ", largest) Largest = 7
Q. Write about iterations and loops in Python.
• Loops in Python allows to repeat a block of code multiple times.
• They are essential for automating repetitive tasks.
• Python has two main types of loops:
1. for loop and
2. while loops.
Q. What is a range in Python?
• In Python, range() is a built-in function that generates a sequence of numbers,
which can be used in loops or converted into a list or tuple.
• It doesn't store all values in memory at once, making it efficient for large ranges.
Syntax:
range(start, stop, step)
• start (optional): The number at which the sequence begins (default is 0).
• stop (required): The number at which the sequence stops (but this value is
excluded).
• step (optional): The difference between each number in the sequence (default is 1).
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 21 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
1. Basic range() with one argument (stop): If you pass only Output-1
one argument to range(), it generates numbers from 0 to
0
that number (exclusive).
Output-2 1
for i in range(4):
print(i) 2 2
2. range() with two arguments (start, stop): 3 3
You can specify where to start and where to stop. 4
for i in range(2, 6): Output-3
5
print(i)
3
3. range() with three arguments (start, stop, step):
You can also define the step 5
(i.e., how much to increment between numbers). 7
for i in range(3, 10, 2): 9
print(i)
Q. What is a for loop in Python?
The for loop in Python is used for iterating over a sequence (like a list, tuple, string, or
range).
Output
Syntax:
for item in sequence: apple
# Code to execute banana
Example: Iterating over a list cherry
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Q. Write a program that can print a message three times on the screen.
Output
for i in range(3): 0 I am a student
print(i, “I am a student”) 1 I am a student
2 I am a student
Q. Write a program that can print sum of the odd series 1 to 20.
Sum = 0 Output
for i in range(1,20,2):
Sum = Sum + i 1 3 5 7 9 11 13 15 17 19
print(i, end=" ") Sum = 100
print("\nSum = ", Sum)
Q. Write a program that can print sum of the even series 1 to 20.
Sum = 0 Output
for i in range(2,21,2):
Sum = Sum + i 2 4 6 8 10 12 14 16 18 20
print(i, end=" ") Sum = 110
print("\nSum = ", Sum)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 22 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can print the pattern.
Output
+
for i in range(5): ++
print((i+1)*'+') +++
++++
+++++
+++++
++++
for i in range(5,0,-1): +++
print((i)*'+') ++
+
Q. Write a program to take input from the user which determines the height of the
diamond and prints a hollow diamond in Python. (Activity 3, Page # 113)
# Get the height of the diamond from the user Output
height=int(input("Enter the height of the diamond: "))
# Upper part of the diamond Enter the height of the diamond: 5
for i in range(1, height + 1): *
# Print leading spaces * *
for j in range(height - i): * *
print(" ", end="") * *
# Print stars and spaces inside the diamond * *
for j in range(2 * i - 1): * *
if j == 0 or j == 2 * i - 2: * *
print("*", end="") * *
else: *
print(" ", end="")
print()
# Lower part of the diamond
for i in range(height - 1, 0, -1):
# Print leading spaces
for j in range(height - i):
print(" ", end="")
# Print stars and spaces inside the diamond
for j in range(2 * i - 1):
if j == 0 or j == 2 * i - 2:
print("*", end="")
else:
print(" ", end="")
print()
Q. Write a program that can print sum of the odd series 1 to 10.
Sum = 0 Output
for i in range(1,10,2):
Sum = Sum + i 1 3 5 7 9
print(i, end=” “) Sum = 25
print("\nSum = ", Sum)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 23 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can print an odd series 1 to 20. Skipping those, divisible by 7.
for i in range(1,20,2): Output
if i%7!=0:
print(i, end=" ") 1 3 5 9 11 13 15 17 19
Q. Write a program that can read a number and calculate its factorial.
Num = int(input("Enter an integer ")) Output
Fact = 1 Enter an integer 5
for i in range(2,Num+1,1): Factorial= 120
Fact = Fact * i
print("Factorial= ", Fact)
Q 2. Write code to take input a number from user and print its mathematical table on screen
from 1 to 10.
Output
Num = int(input("Enter an integer ")) Enter an integer 2
for c in range(10): 2 x 1 = 2
c=c+1 2 x 2 = 4
print(Num," x ",c," = ",Num*c) 2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Q. Write a program that can accept a number and check if it is Prime or Composite.
n = int(input("Enter an integer ")) Output
Prime = 1
for i in range(2,n): Enter an integer 3
if n%i==0: The number is Prime
Prime = 0
if Prime == 1: Output
print("The number is Prime ")
else: Enter an integer 9
print("The number is Composite ") The number is Composite
Q. Write a program that can accept two numbers and print GCD.
a = int(input("Enter integer a: ")) Output
b = int(input("Enter integer b: "))
end = min(a,b) Enter integer a: 64
GCD = 1 Enter integer b: 16
for c in range(2,end+1): Greater Common Devisor = 16
if a%c==0 and b%c==0:
GCD=c
print("Greater Common Devisor = ", GCD)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 24 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can accept two numbers and print HCF and LCM.
a = int(input("Enter an integer a ")) Output
b = int(input("Enter an integer b "))
MIN = min(a,b) Enter an integer a 16
HCF = 1 Enter an integer b 64
for i in range(1,MIN+1): HCF = 8
if a%i==0 and b%i==0: LCM = 128
HCF = i
print("HCF = ", HCF)
# LCM * HCF = a * b
LCM =a*b//HCF
print("LCM = ", LCM)
Q. Write about the nested loop in Python.
• A loop inside other loop is called a nested loop.
• The "outer loop" runs first, and for every iteration of the outer loop, the "inner loop"
runs completely before moving on to the next iteration of the outer loop.
• Nested loops are often used when working with multidimensional data structures,
like matrices or when generating patterns.
Syntax:
for i in range(outer_loop_count):
for j in range(inner_loop_count):
# Inner loop code
Q. Write a program that can print the pattern.
for i in range(5): Output
for j in range(5): * * * * *
print('*', end=" ") * * * * *
print() * * * * *
* * * * *
* * * * *
Q. Write a program that can print the pattern.
for i in range(5): Output
for j in range(5): 0 1 2 3 4
print(j, end=" ") 0 1 2 3 4
print() 0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
Q. Write a program that can print the pattern.
for i in range(5): Output
for j in range(5): 0 0 0 0 0
print(i, end=" ") 1 1 1 1 1
print() 2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 25 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can print the pattern.
for i in range(5): Output
for j in range(i+1): *
print('*', end=" ") * *
print() * * *
* * * *
* * * * *
Q. Write a program that can print the pattern.
for i in range(5): Output
for j in range(i+1): 0
print(j, end=" ") 0 1
print() 0 1 2
0 1 2 3
0 1 2 3 4
Q. Write a program that can print the pattern.
for i in range(5): Output
for j in range(i+1): 0
print(i, end=" ") 1 1
print() 2 2 2
3 3 3 3
4 4 4 4 4
Q. Write a program that can print the pattern.
for i in range(5, 0, -1): Output
for j in range(i): 0 1 2 3 4
print(j, end=" ") 0 1 2 3
print() 0 1 2
0 1
0
Q. Write a program that can print the pattern.
for i in range(5, 0, -1): Output
for j in range(i): * * * * *
print(‘*’, end=" ") * * * *
print() * * *
* *
*
Q. Write a program that can print the pattern.
for i in range(5, -1, -1): Output
for j in range(i,5,1): 4
print(j, end=" ") 3 4
print() 2 3 4
1 2 3 4
0 1 2 3 4
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 26 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. What is a while loop in Python?
• A while loop in Python repeatedly executes a block of code as long as a given
condition is True.
• The condition is checked before each iteration, and if it evaluates to False, the loop
stops running.
• This makes the while loop useful for situations where the number of iterations is
not known in advance.
Output
Syntax:
while condition: 1
# Code to execute 2
Example: 3
count = 1
4
while count <= 5:
print(count) 5
count += 1 # increment the count to avoid an infinite loop
Q 3. Take an odd number as input from the user, check if it is odd, otherwise ask the user
to re-enter an off number.
c = True Output
while c:
number = eval(input("Enter an odd number: ")) Enter an odd number: 2
if number % 2 != 0: Enter an odd number: 4
print(f"Great! {number} is an odd number.") Enter an odd number: 6
c = False Enter an odd number: 5
else: Great! 5 is an odd number.
c = True
Q. Write a Python program to count even and odd numbers in a list using while loop.
(Model Paper Q 5.)
List = [1,2,3,4,5,6,7,8,9] Output
even_count = 0
odd_count = 0 Even numbers count: 4
index = 0 Odd numbers count: 5
while index < len(List):
if List[index] % 2 == 0:
even_count += 1
else:
odd_count += 1
index += 1
print("Even numbers count: ", even_count)
print("Odd numbers count: ", odd_count)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 27 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q 4. Write down the main examples of Python based applications.
Ans.
1. Web Development
• Frameworks: Django, Flask, FastAPI.
• Examples:
o Instagram: Uses Django for its backend.
o Spotify: Employs Python for backend services.
2. Data Science and Machine Learning
• Libraries: NumPy, pandas, scikit-learn, TensorFlow, PyTorch.
• Examples:
o Predictive analytics for finance, healthcare, or marketing.
o Fraud detection systems.
3. Artificial Intelligence (AI)
• Applications: Natural Language Processing (NLP), computer vision, robotics.
• Examples:
o Chatbots like OpenAI's GPT.
o Autonomous cars (computer vision applications).
Q. Write a program that can read a user input and print it. Repeat the process until user
enter ‘0’.
number = int(input("Enter a number (0 to stop): "))
while number != 0:
print(f"You entered {number}. Try again.") # f is used for format string, {} used for value
number = int(input("Enter a number (0 to stop): "))
print("You exited the loop!")
Output
Enter a number (0 to stop): 3
You entered 3. Try again.
Enter a number (0 to stop): 7
You entered 7. Try again.
Enter a number (0 to stop): 0
You exited the loop!
Q. Differentiate between break and continue statement.
• The break statement is used to exit a • The continue statement is used to
loop prematurely. skip the current iteration of a loop
• When the break statement is and proceed to the next iteration.
executed inside a loop, it • When continue is executed, the
immediately terminates the loop, remaining code in the loop for that
and the program continues to iteration is skipped, and the loop
execute the code that follows the moves on to the next cycle
loop. (iteration).
Syntax: Syntax:
break continue
Example: Example of continue:
for i in range(1, 6): # Example: Using continue to skip certain
print(i) iterations
if i == 3: for i in range(1, 6):
break # Exit the loop when i is 3 if i == 3:
continue # Skip the iteration when i is 3
print(i)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 28 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Output: Output:
1 1
2 2
3 4
5
Q. How lists are used in Python?
• In Python, a list is a built-in data structure that allows you to store an ordered
collection of items.
• These items can be of different types (integers, floats, strings, other lists, etc.).
• Lists are mutable, which means you can modify their contents (add, remove, or
change items) after they are created.
• Lists are created by placing the items inside square brackets [], separated by
commas.
Syntax:
my_list = [element1, element2, element3, element4, element5]
Example:
my_list = [1, 2, 3, "apple", "banana", [10, 20]]
• You can access items in a list using their index (starting from 0).
• Access the first element
print(my_list[0]) # Output: 1
• Access the last element (nested list)
print(my_list[-1]) # Output: [10, 20]
• Changing the value of an element in a list by assigning a new value to specific index.
my_list[1] = "orange"
print(my_list) # Output: [1, 'orange', 3, 'apple', 'banana', [10, 20]]
Q. Define len() with its syntax used in Python.
• The len() function in Python is a built-in function that returns the number of items
in an object.
• It is most commonly used to determine the length of strings, lists, tuples,
dictionaries, sets, and other collections.
Syntax:
len(object)
Example:
Series[1,2,3,4,5,6,7,8,9]
Print(“Number of elements = “, len(Series))
Output: Number of elements = 9
Q. Define min() with its syntax used in Python?
• The min() function in Python is a built-in function that returns the smallest element
from a given iterable or from multiple provided values.
Syntax:
min(iterable)
min(arg1, arg2, *arg)
• iterable: Any iterable object like a list, tuple, set, etc.
• arg1, arg2, *args: Multiple values separated by commas.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 29 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Define max() with its syntax used in Python?
• The max() function in Python is used to find the maximum value among the
elements of an iterable (such as a list, tuple, set) or among two or more arguments.
Syntax:
max(iterable, *[, key, default])min(arg1, arg2, *arg)
max(arg1, arg2, *args[, key])
• iterable: A sequence (like a list, tuple, etc.)
• arg1, arg2, *args: Two or more arguments can be provided directly.
• key (optional): A function where each element is passed and comparison is done
based on the returned value.
• default (optional): A default value to return if the iterable is empty.
Q. Define sum() with its syntax used in Python?
• The sum() function in Python is a built-in function that returns the sum of all
elements in an iterable, such as a list, tuple, or set.
• It can also include an optional start value that is added to the sum of the elements.
Syntax:
sum(iterable, start=0)
• iterable: The object whose elements you want to sum up (e.g., list, tuple, set).
• start (optional): A value to add to the total. The default is 0.
Q. Write a program that can read 5 elements print the list, maximum, minimum values,
length and sum of elements.
List=[4,1,6,9,8] Output
for i in List: 4 1 6 9 8
print(i, end=" ") Maximum value = 9
print() Minimum value = 1
print("Maximum value = ", max(List)) Number of elements = 5
print("Minimum value = ", min(List)) Sum of all values = 28
print("Number of elements = ", len(List))
print("Sum of all values = ", sum(List))
Q. Define insert() with its syntax used in Python?
• The insert() function in Python is a method used with lists to insert an element at a
specific position.
• It modifies the original list by placing the new element at the specified index, shifting
existing elements to the right.
Syntax:
list.insert(index, element)
• index: Position at which to insert the element. Indexing in Python starts from 0.
• element: The element you want to insert into the list.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 30 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Define index() with its syntax used in Python?
• The index() function in Python is a method used with sequences like lists, strings, or
tuples to find the first occurrence of a specified element.
• It returns the index (position) of that element in the sequence.
Syntax:
list.index(element, start=0, end=len(list))
• element: The element whose index you want to find.
• start (optional): The position to start searching from. By default, it is 0.
• end (optional): The position to stop searching at. By default, it is the length of list.
Q. Write a program that can add an element and print index number of that element.
List=[4,1,6,9,8] Output
print("List before inserting an element") List before inserting an element
print(List) [4, 1, 6, 9, 8]
List.insert(4,9) List after inserting an element
print("List after inserting an element") [4, 1, 6, 9, 9, 8]
print(List) First 9 found on index: 3
print("First 9 found on index: ",List.index(9))
Q. Complete the following Python code that exits when x is “Physics”.
(Model Paper Q 2. xiii)
Subjects=[“Computer”, “English”, “Physics”] Subjects=[“Computer”, “English”, “Physics”]
for x in __________: for x in range(len(Subjects):
if x == __________: if x == 2:
_____________ break
print(x) print(x)
Q. Write a program that can read 5 elements a list and print them in reverse order.
List=[] Output
for i in range(5): Enter integer 1
element=int(input("Enter integer ")) Enter integer 2
List.append(element) Enter integer 3
print("Reverse order") Enter integer 4
for i in range(4,-1,-1): Enter integer 5
print(List[i], end=” “) Reverse order
5 4 3 2 1
Q. Write a program that can read 5 elements a list and print smallest among list.
List=[] Output
for i in range(5): Enter integer 9
element=int(input("Enter integer ")) Enter integer 3
List.append(element) Enter integer 7
smallest = List[0] Enter integer 1
for i in range(1,5,1): Enter integer 4
if List[i] < smallest:
smallest = List[i] Smallest = 1
print("\nSmallest = ", smallest)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 31 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can read 5 elements a list and print largest among list.
List=[] Output
for i in range(5): Enter integer 9
element=int(input("Enter integer ")) Enter integer 3
List.append(element) Enter integer 7
largest = List[0] Enter integer 1
for i in range(1,5,1): Enter integer 4
if List[i] > largest:
largest = List[i] Largest = 1
print("\nLargest = ", largest)
Q. Write a program that can read elements from given list and sum only positive numbers.
Sum = 0 Output
List=[1, -20, 2, -19, 3, 4, -1, -15, -2, -3]
for i in range(10): Sum = 10
if List[i] > 0:
Sum = Sum + List[i]
print("\nSum = ", Sum)
Q. Write a program that can read a list of numbers and sort them using insertion sort.
List=[] Output
for i in range(5):
element=int(input("Enter integer ")) Enter integer 0
List.append(element) Enter integer 9
print("Sorted List") Enter integer 1
for i in range(1,len(List)): Enter integer 8
key = List[i] Enter integer 2
j=i-1 Sorted List
while j >= 0 and key < List[j]: [ 0, 1, 2, 8, 9 ]
List[j + 1] = List[j]
j -= 1
List[j + 1] = key
print(List)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 32 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can read a list of numbers and sort them using bubble sort.
arr=[] Output
for i in range(5):
element=int(input("Enter integer ")) Enter integer 5
arr.append(element) Enter integer 1
print("Original List:", arr) Enter integer 4
n = len(arr) Enter integer 3
# Traverse through all elements in the list Enter integer 2
for i in range(n): Original List: [5, 1, 4, 3, 2]
# Track whether a swap occurred during the pass Sorted List: [1, 2, 3, 4, 5]
swapped = False
# Last i elements are already sorted, no need to check them
for j in range(0, n - i - 1):
# Compare adjacent elements
if arr[j] > arr[j + 1]:
# Swap if the element is greater than the next one
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
# If no two elements were swapped in the inner loop, the list
is sorted
if not swapped:
break
print("Sorted List:", arr)
Q. How tuples are used in Python?
• In Python, a tuple is a built-in data structure that allows you to store an ordered
collection of items.
• These items can be of different types (integers, floats, strings, other lists, etc.).
• Tuples are immutable, which means you cannot be changed or modified after they
are created.
• Tuples are created by placing the items inside parentheses (), separated by commas.
Syntax:
my_tuple = (element1, element2, element3, element4, element5)
Example:
my_tuple = (1, “apple”, 3.14, True)
• You can access items in a tuple using their index (starting from 0) just like lists.
• Access the element
print(my_tuple[1]) # Output: “apple”
• Access the last element
print(my_tuple[-1]) # Output: True
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 33 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can read 5 elements print the tuple, maximum, minimum values,
length and sum of elements.
Tuple =(4,1,6,9,8) Output
for i in Tuple: 4 1 6 9 8
print(i, end=" ") Maximum value = 9
print() Minimum value = 1
print("Maximum value = ", max(Tuple)) Number of elements = 5
print("Minimum value = ", min(Tuple)) Sum of all values = 28
print("Number of elements = ", len(Tuple))
print("Sum of all values = ", sum(Tuple))
Q. What is the random module in Python? How we can use it?
• The random module in Python is a built-in module that provides functions for
generating random numbers and performing random operations.
• It is useful for tasks like simulations, random sampling, and game development.
• This module offers tools to generate random integers, floats, and sequences, as well
as functions to shuffle data or make random selections.
Q. What is the randint() function in Python?
• It returns a random integer between two values (both inclusive).
• It is available in random module of Python.
Syntax:
randint(start value, end value)
Example:
randint(1, 10) # returns 5
• It will return a random value between 1 to 10 (inclusive 1 and 10)
Q. What is the abs() function in Python?
• The abs() function in Python returns the absolute value of a given number.
• The absolute value of a number is its non-negative value, regardless of its sign.
Syntax:
abs(number)
Example:
abs(- 5 ) # returns 5
• It will return 5 that is a non-zero value.
Q. Write a program that can take a two-digit number. Subtract it from 100 and calculate
the difference and print it. (Activity # 4, Page # 114)
from random import randint Output
Number = randint(10, 99)
Difference = 100 - Number Random number is = 78
print("Random number is = ", Number) Difference = 22
print("Difference = ",Difference)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 34 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that defines an empty list. Populate it with 10 random numbers and
print it.
from random import randint Output
Rnums = []
for i in range(10): [21, 42, 41, 52, 27, 19, 97, 21, 61, 46]
Rnums.append(randint(1,99))
print(Rnums)
Q. Write down the purpose of append() function.
• The append() function in Python is a method used with lists to add an element to
the end of the list.
• It modifies the original list in place and does not return any value.
Syntax:
list.append(element)
Example:
MyList = [1,2,3]
MyList.append(4)
print(MyLIst) # Output: [1,2,3,4]
• Elements of different data types can be appended in the list.
Q. Write a program that assign a number to search in the list. Initialize an empty list and
populate it with 10 random numbers between 1 to 99 and search the given number in the
list. (Fig. 3.30, Page # 113)
from random import randint Output
numseek = 7
temp = 0 [90, 17, 84, 1, 26, 50, 80, 74, 6, 52]
Rnum = [] 7 is not in the list
for i in range(10):
Rnum.append(randint(1,99))
print(Rnum)
for i in range(len(Rnum)):
if(numseek == Rnum[i]):
temp = temp + 1
if temp > 0:
print("7 is on index: ", Rnum.index(7))
else:
print("7 is not in the list")
Q. Initialize a list with four elements and check the presence of an element in the list.
L = [1, 2, 5, 7] Output
print(5 in L) True
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 35 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Define a function in Python. Write its basic syntax.
• In Python, a function is a reusable block of code that performs a specific task.
• Functions help organize code, make it modular, and avoid repetition.
Syntax:
def function_name(parameters):
# code to execute
return result # optional
• To define a function, use the def keyword, followed by the function name,
parentheses (), and a colon :.
• Inside the parentheses, you can specify parameters (inputs).
Example:
def add_number( x , y ):
result = x + y
return result
Function Call:
sum_result = add_number( 5 , 3 )
print(sum_result) # Output: 8
Q. Write down the types of function in Python.
• There are two types of functions:
o Build-in Functions/ Library Functions
o User-defined functions
Build-in Function/ Library Functions:
• Build-in functions or pre-defined functions or Library functions are those functions
which are already defined in Python library.
• We can use these functions in our programs for different purposes.
• For example, sum(), min(), max() etc.
User-defined Functions
• Functions defined by the user/ programmer that are not available in the library.
• User can define their own function using def keyword to fulfill the reuirements.
• For example,
def average( x , y ):
result = (x + y)/2
return result
# Function Call:
avg = average( 5 , 3 )
print(avg) # Output: 4
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 36 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Differentiate between local and global variables used in Python.
Local Variables Global Variables
Definition: Local variables are defined inside Definition: A global variable is defined
the function (block of code). outside any function or block, typically at
Scope: Its scope is limited to the function in the top level of a script or module.
which it is defined. Scope: Its scope is global to the entire
Once the function completes execution, the program or module, meaning it is accessible
local variable is destroyed. from anywhere in the program after its
Life Time: A local variable exists only during definition.
the execution of the function or block where Life Time: A global variable exists for the
it is declared. lifetime of the program.
def add(a, b): # a and b are local variables
Sum = a + b
print("Value of x = ",x) # x is accessible in this block
print("Value of y = ",y) # y is accessible in this block
print("Sum = ", Sum)
x = eval(input("Enter an integer ")) # x is a global variable
y = eval(input("Enter an integer ")) # y is a global variable
# Function call
add(x, y)
Q. Differentiate between actual and formal parameters/arguments in Python.
Actual Parameters/Arguments Formal Parameters/Arguments
• Arguments used in the function call are • Arguments used in the function
called actual arguments. definition are called formal arguments.
• Actual arguments pass their values to • Formal arguments receive their values
formal arguments. from actual arguments.
def add(a, b): #.................................................a and b are formal arguments
Sum = a + b
print("Sum = ", Sum)
x = eval(input("Enter an integer "))
y = eval(input("Enter an integer "))
# Function call
add(x, y) #.................................................x and y are actual arguments
Q. Write a program that can define a function to draw a line.
def draw_line(): Output
print('_' * 10) __________
draw_line()
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 37 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can draw horizontal and vertical lines using functions.
Fig. 3.33, Page # 116
def draw_h_line(): Output
print('-'*20) --------------------
def draw_v_parallel_line(): | |
print('|',' '*16,'|') | |
draw_h_line() | |
draw_v_parallel_line() | |
draw_v_parallel_line() --------------------
draw_v_parallel_line()
draw_v_parallel_line()
draw_h_line()
Q. Write a program that can draw horizontal and vertical lines using arguments in
functions. Fig. 3.34, Page # 117
def draw_h_line(n): Output
print('-'*n) --------------------
def draw_v_parallel_line(m): | |
print('|',' '*m,'|') | |
draw_h_line(20) | |
draw_v_parallel_line(16) | |
draw_v_parallel_line(16) --------------------
draw_v_parallel_line(16)
draw_v_parallel_line(16)
draw_h_line(20)
Q. Write a program that can draw horizontal and vertical lines using multiple arguments
in functions. Fig. 3.35, Page # 117
def draw_hline(n,o): Output
print(o*n) ==========
def draw_v_parallel_lines(l,m): || ||
print(l,' '*m,l) || ||
draw_hline(10, '=') || ||
draw_v_parallel_lines('||',4) || ||
draw_v_parallel_lines('||',4) ==========
draw_v_parallel_lines('||',4)
draw_v_parallel_lines('||',4)
draw_hline(10,'=')
Q. Write a program that can return the sum of a list using a function. Fig. 3.36, Page # 117
L_of_num = [7,8,9,10,11] Output
def list_sumup():
sum = 0 45
for I in range(5):
sum+=L_of_num[I]
return (sum)
print(list_sumup())
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 38 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write about the return statement.
• In Python, the return statement is used in a function to send a value back to the
calling statement.
• It marks the end of the function's execution and specifies the result that the
function should produce.
Syntax:
return [expression]
• Here, expression is optional. It can be a value, a variable, or a computation.
• If no expression is provided, the function returns None by default.
Q. Write a program that can define a function to add two numbers.
def add(a,b): Output
Sum = a + b
print("Sum = ", Sum) Enter an integer 2
x = eval(input("Enter an integer ")) Enter an integer 4
y = eval(input("Enter an integer ")) Sum = 6
# Function call
add(x,y)
Q. Write a program that can define a function to add two numbers and returns the result.
def add(a,b): Output
Sum = a + b
return Sum Enter an integer 2
x = eval(input("Enter an integer ")) Enter an integer 4
y = eval(input("Enter an integer ")) Sum = 6
Sum = add(x,y)
print("Sum = ", Sum)
Q. Write a Python function find_max() that takes two numbers as input and returns the
maximum number. (Model Paper Q 2. xiii)
def find_max(num1, num2): Output
return max(num1, num2)
Enter a number: 5
a = eval(input("Enter a number: ")) Enter a number: 6
b = eval(input("Enter a number: ")) Maximum value = 6
maximum = find_max(a,b)
print("Maximum value = ", maximum)
Q. Write a program that can accept length and width for a rectangle and print its area
using function.
def area( length, width ): Output
a = length * width
return a Enter length for a rectangle 4.5
#Function Call: Enter width for a rectangle 3.6
L = eval(input("Enter length for a rectangle ")) Area of rectangle = 16.2
W = eval(input("Enter width for a rectangle "))
a = area(L, W)
print("Area of rectangle = ", a)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 39 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can accept radius for a circle and calculate its area using function.
def area( radius ): Output
a = 3.1412 * radius * radius
return a Enter radius for a circle 3.5
#Function Call: Area of circle = 38.479699999999994
r = eval(input("Enter radius for a circle "))
a = area( r )
print("Area of circle = ", a)
Q. Write a Python program to compute the area of circle and rectangle by using function.
(Model Paper Q 3.)
# Function to calculate the area of a circle
def area_of_circle(radius):
return 3.1412 * radius ** 2
# Function to calculate the area of a rectangle
def area_of_rectangle(length, width):
return length * width
print("Choose the shape to calculate the area:")
print("1. Circle")
print("2. Rectangle")
choice = int(input("Enter your choice (1 or 2): "))
if choice == 1:
radius = float(input("Enter the radius of the circle: "))
area = area_of_circle(radius)
print("The area of the circle with radius “,radius, “is “,area)
elif choice == 2:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = area_of_rectangle(length, width)
print("The area of the rectangle with length “,length, “and width “, width, “ is “,area)
else:
print("Invalid choice. Please select 1 or 2.")
Q. Write a program that can accept a number and check if it is even or an odd number
using function.
def even_odd( number ): Output
if number % 2 == 0:
return "EVEN" Enter an integer 5
else: The number is ODD
return "ODD"
#Function Call:
num = eval(input("Enter an integer "))
result = even_odd( num )
print("The number is ", result)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 40 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can accept a number and check if it is positive, negative or neutral
number using function.
def positive_negative( number ): Output
if number > 0:
return "POSITIVE" Enter an integer -5
elif number < 0: The number is NEGATIVE
return "NEGATIVE"
else:
return "NEUTRAL"
#Function Call:
num = eval(input("Enter an integer "))
result = positive_negative( num )
print("The number is ", result)
Q. Write a program that can accept marks for a student and check it pass or fail using
function. Total marks are 100 and passing marks are 40.
def pass_fail( marks ): Output
if marks >= 40:
return "PASS" Enter marks for a student 90
else: The student is PASS
return "FAIL"
#Function Call:
m = eval(input("Enter marks for a student "))
result = pass_fail( m )
print("The student is ", result)
Q. Write a program that can accept a number and calculate its factorial using function.
def factorial( n ): Output
fact = 1
for i in range(2,n+1,1): Enter an integer 6
fact = fact * i Factorial = 720
return fact
#Function Call:
x = eval(input("Enter an integer "))
f = factorial(x)
print("Factorial = ", f)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 41 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that can accept a letter and check if vowel or consonant using
function.
def Vowel(Letter): Output
if Letter == 'a' or Letter == 'A':
print("Vowel") Enter a letter a
elif Letter == 'e' or Letter == 'E': Vowel
print("Vowel")
elif Letter == 'i' or Letter == 'I':
print("Vowel")
elif Letter == 'o' or Letter == 'O':
print("Vowel")
elif Letter == 'u' or Letter == 'U':
print("Vowel")
else:
print("Consonent")
# Function call
Alphabet = input("Enter a letter ")
Vowel(Alphabet)
Q. Write a program that can define a function to take input from user and print a table.
(Activity 5, Page # 116 )
def table(n): Output
for c in range(10): Enter Table number 2
c=c+1 2 x 1 = 2
print(n, ' x ', c, ' = ', n*c) 2 x 2 = 4
t = eval(input("Enter Table number ")) 2 x 3 = 6
table(t) 2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Q. Define bugs and debugging in Python.
• bugs are errors, flaws, or mistakes in a program that cause it to behave
unexpectedly or incorrectly.
• Debugging is the process of identifying, analyzing, and fixing bugs in a program.
• It involves systematically inspecting code, testing it, and resolving errors to ensure
the program behaves as expected.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 42 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. How to activate Debugger IDE?
• Open Python IDLE shell
• From menu select “Debug” then “Debugger” the “Debug Control” window will
open.
• Open a program like “Swap.py” and run it using “Run” command or press “F5”.
Q 4. How to locate and select Debugger in IDLE? Write steps by taking an example into
consideration.
Ans.
Steps to Enable and Use Debugger in IDLE:
1. Open IDLE:
o Launch the IDLE application from your system. You can typically find it installed
along with Python.
2. Open Your Script:
o If you already have a Python script, open it by clicking File > Open and selecting
your file.
o For this example, let's consider a simple script called example.py with the
following content:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
num = 5
print(f"The factorial of {num} is {factorial(num)}")
3. Enable Debugger:
o In the IDLE editor, go to the Debug menu in the top navigation bar.
o Select Debugger. This will enable debugging mode. You should see a
checkmark next to it when it's activated.
4. Set Breakpoints:
o Place your cursor on the line where you want the program to pause.
o To set a breakpoint, click Debug > Set Breakpoint or press Ctrl+B.
For our example, you might set a breakpoint on the line return n * factorial(n - 1) to observe
the recursive calls.
5. Run the Script in Debug Mode:
o Go to Run > Run Module or press F5. The debugger will start, and the script
will run until it hits the breakpoint.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 43 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
6. Use Debugger Controls:
o Once the script pauses at a breakpoint, the Debug Control panel will open.
o You can use the following buttons:
▪ Step: Executes the current line and moves to the next.
▪ Over: Steps over function calls.
▪ Out: Runs until the current function returns.
▪ Go: Resumes execution until the next breakpoint or the end of the
program.
▪ Quit: Stops the debugger.
7. Inspect Variables:
o While paused, inspect variable values by hovering over them or checking the
Local and Global variable panels in the debugger.
Example Debugging Session:
• When the breakpoint at return n * factorial(n - 1) is hit, you can step through each
recursive call.
• Watch how the n and return values change, helping you understand the flow of
recursion.
Q 5. Write code to print the multiplication of first 10 odd numbers and first 10 even
numbers and find the difference of two.
Ans.
# Calculate the product of the first 10 odd numbers
product_odd = 1
for num in range(1,20, 2):
product_odd *= num
# Calculate the product of the first 10 even numbers
product_even = 1
for num in range(2,21,2):
product_even *= num
# Print the results
print("Product of first 10 odd numbers:", product_odd)
print("Product of first 10 even numbers:", product_even)
# Calculate and print the difference
difference = abs(product_odd - product_even)
print("Difference between the two products:", difference)
Q. Write about the components of Debug Control window.
Step Button: It allows to execute the code line-by-line.
Go Button: It allows to jump to a break point.
Over Button: It is used when there is a function call and wants to avoid it completely.
Out Button: It is used while examining in a function and wants to skip the remaining
portion.
Global and Local check boxes: Reflects the Global and Local data respectively.
Source check box: Refers the currently running file.
Stack check box: Highlights the function currently running in the debugger.
Breakpoints: A breakpoint is the line of code which needs close examination, so the
debugger will stopover there definitely.
Set Breakpoint: Right-click on the line and from shortcut menu select Set Breakpoint.
Clear Break Point: Right-click on the line and from shortcut menu select Clear Breakpoint.
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 44 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. What is a Python Debugger (pdb)?
• Python Debugger (pdb) is a Python debugger library.
• In the command prompt go to the Python directory i.e. C:\Python\Python312>
• Type the command: Python -m pdb swap.py (swap.py file must be present there)
• -m switch allows Python to run the imported module as a script.
• Breakpoints may be assigned via break line_number like break 7
• continue command is used to move the debugger directly to the breakpoint.
• list command is used to display a few lines of source code around the current line.
• step command to execute code line-by-line.
Q. How to activate Python Debugger (pdb) using Python source file?
• Python also gives the option to import the pdb in the code, as the first line of
program.
• When program starts, debugger stops at the first line.
• Next, step command can be used to move forward.
• pdb.set_trace() command is used to assign breakpoints in the code.
Q. How to use print statement for debugging?
• By placing multiple print statements thoughtfully, a smooth traceability of any bug
can be achieved.
• Use print statement after each statement where to assigning new values to the
variables.
• The corresponding output allows us to identify the bugs.
Q. How to use assert statement in Python?
• The assert statement in Python is a debugging tool that tests a condition.
• If the condition evaluates to True, the program continues executing normally.
• However, if the condition evaluates to False, Python raises an AssertionError with
an optional error message.
x = -5
assert x > 0, "x must be positive!" # Raises AssertionError with the message
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 45 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program that takes input from user which determines the height of the
diamond and print a filled diamond in python. (Activity 6, Page # 122)
# Take input for the height of the diamond
height = int(input("Enter the height of the diamond (odd number): "))
# Ensure height is an odd number
if height % 2 == 0:
print("Please enter an odd number for the height.")
else:
# Calculate the middle point of the diamond
mid = height // 2
# Print the upper part of the diamond
for i in range(mid + 1):
spaces = mid - i
stars = 2 * i + 1
print(" " * spaces + "*" * stars)
# Print the lower part of the diamond
for i in range(mid - 1, -1, -1):
spaces = mid - i
stars = 2 * i + 1
print(" " * spaces + "*" * stars)
Q. Write a turtle graphics code to draw a Tic Tac Toe Board. (Activity 7, Page # 122)
import turtle
def draw_tic_tac_toe_board():
screen = turtle.Screen()
screen.title("Tic Tac Toe Board")
screen.setup(width=400, height=400)
t = turtle.Turtle()
t.speed(3)
# Draw vertical lines
t.penup()
t.goto(-50, 150)
t.pendown()
t.goto(-50, -150)
t.penup()
t.goto(50, 150)
t.pendown()
t.goto(50, -150)
# Draw horizontal lines
t.penup()
t.goto(-150, 50)
t.pendown()
t.goto(150, 50)
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 46 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
t.penup()
t.goto(-150, -50)
t.pendown()
t.goto(150, -50)
t.penup()
t.hideturtle()
screen.mainloop()
draw_tic_tac_toe_board()
Q. Write a turtle graphics code to draw a Tic-Tac-Toe board. (Activity 7, Page # 122)
import turtle
def draw_line(x1, y1, x2, y2):
"""Draws a line from (x1, y1) to (x2, y2)."""
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
turtle.goto(x2, y2)
def draw_tic_tac_toe_board():
"""Draws a Tic-Tac-Toe board."""
turtle.speed(5)
# Vertical lines
draw_line(-100, 300, -100, -300)
draw_line(100, 300, 100, -300)
# Horizontal lines
draw_line(-300, 100, 300, 100)
draw_line(-300, -100, 300, -100)
turtle.hideturtle()
turtle.done()
# Call the function to draw the board
draw_tic_tac_toe_board()
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 47 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Take an odd number as input from the user and draw a ‘X’ with the help of a character like ‘+’.
The input number defines the size of ‘X’ to be displayed. (Activity 8, Page # 122)
def draw_x(height, char):
for i in range(height):
for j in range(height):
if i == j or i + j == height - 1:
print(char, end="")
else:
print(" ", end="")
print()
def main():
while True:
try:
height = int(input("Enter an odd number for the height of the 'X': "))
if height % 2 == 0 or height <= 0:
print("Please enter a positive odd number.")
else:
break
except ValueError:
print("Invalid input. Please enter a valid odd number.")
char = input("Enter the character to draw the 'X': ")
if not char:
char = '+' # Default character
print("\nDrawing 'X':\n")
draw_x(height, char)
if __name__ == "__main__":
main()
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 48 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program to calculate how many iterations it takes to subtract a small number from a
large one, where both the numbers are positive integrals. (Activity 9)
def calculate_iterations():
try:
large_number = int(input("Enter the larger positive integer: "))
small_number = int(input("Enter the smaller positive integer: "))
if large_number <= 0 or small_number <= 0:
print("Both numbers must be positive integers.")
return
if small_number > large_number:
print("The smaller number should be less than or equal to the larger number.")
return
iterations = 0
while large_number > 0:
large_number -= small_number
iterations += 1
print(f"It takes {iterations} iterations to reduce the larger number to 0 or less.")
except ValueError:
print("Invalid input. Please enter positive integers only.")
# Run the function
calculate_iterations()
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 49 of 50
Prepared by: Ahmed Hassan Khan Programming Fundamentals First Year Chapter # 3
Q. Write a program for a Dice Rolling Race Game for 2 Players. Alternatively, generate an
random number for each player. If the number rolls out to be 6, then the player gets another
roll. Rolls of every iteration is summed up to the previous rolls. The player who reaches 10.
(Exercise Long Q # 3, Page # 126 )
Ans.
import random
def roll_dice():
"""Simulates rolling a dice, returns a number between 1 and 6."""
return random.randint(1, 6)
def play_turn(player_name, current_score):
"""Simulates a player's turn, rolling the dice and accumulating their score."""
turn_total = 0
while True:
roll = roll_dice()
print(player_name, " rolled a ", roll)
turn_total += roll
if roll != 6: # If the roll is not 6, end the turn.
break
else:
print(player_name, " gets another roll for rolling a 6!", end=" ")
input()
current_score += turn_total
print(player_name, "'s total score is now ",current_score)
return current_score
#Game starts here
print("Welcome to the Dice Rolling Race Game!")
player1 = input("Enter name of player 1 ")
player2 = input("Enter name of player 2 ")
score1 = 0
score2 = 0
winning_score = 10
while score1 < winning_score and score2 < winning_score:
print("\n",player1,"'s turn: Press enter to roll the dice", end=" ")
input()
score1 = play_turn(player1, score1)
if score1 >= winning_score:
print("Congratulations", player1, " you win!")
break
print("\n",player2, "'s turn: Press enter to roll the dice", end=" ")
input()
score2 = play_turn(player2, score2)
if score2 >= winning_score:
print("Congratulations", player2," you win!")
break
Punjab College of Comm. Cantt. Campus Updated 23/09/2024 Page 50 of 50