0% found this document useful (0 votes)
3 views31 pages

Python Important Programs

The document provides a series of Python programming examples that demonstrate various concepts such as converting time units, summing user inputs, and checking for palindromes. Each example includes a question, the corresponding Python code, and explanations of the logic behind the code. The document serves as a practical guide for learning Python programming through hands-on examples.

Uploaded by

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

Python Important Programs

The document provides a series of Python programming examples that demonstrate various concepts such as converting time units, summing user inputs, and checking for palindromes. Each example includes a question, the corresponding Python code, and explanations of the logic behind the code. The document serves as a practical guide for learning Python programming through hands-on examples.

Uploaded by

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

Python Important Programs

June 9, 2025

om
www.acadflix.com Phone: +91-9911082011

.c
Example Program 1

ix x
fl li
Question 1: Write a program that asks the user to input number of seconds, and then
expresses it in terms of how many minutes and seconds it contains.

Python Program
ad df
# Ask the user to enter the number of seconds
num_seconds = int ( input ( " Enter number of seconds : " ))
ac ca

# Calculate the number of full minutes


num_minutes = num_seconds // 60

# Calculate the remaining seconds after taking out the full minutes
w. A

remaining_ secon ds = num_seconds % 60

# Display the result


print ( " Minutes : " , num_minutes )
print ( " Seconds : " , remain ing_s econds )

Explanation (in simple terms)


ww

The user enters any number of seconds. For example, if the user types 135 seconds:

• One minute has 60 seconds.

• To find full minutes, divide by 60: // 60.

• To find leftover seconds, use % 60.

1
Example Output
Enter number of seconds: 135
Minutes: 2
Seconds: 15

Example Program 2
Question 2: Write a program to convert total number of days into weeks and days.

om
Python Program
# Ask user to enter total number of days

.c
total_days = int ( input ( " Enter total number of days : " ))

ix x
# Calculate number of weeks
fl li
weeks = total_days // 7

# Calculate remaining days


remaining_days = total_days % 7
ad df
# Display result
print ( " Weeks : " , weeks )
print ( " Days : " , remaining_days )
ac ca

Example Output
w. A

Enter total number of days: 17


Weeks: 2
Days: 3

Example Program 3
ww

Question 3: Write a program to input number of minutes and convert it to hours and
minutes.

Python Program
# Ask user to enter number of minutes
num_minutes = int ( input ( " Enter number of minutes : " ))

# Calculate number of hours


hours = num_minutes // 60
# Calculate remaining minutes
remaining_ minut es = num_minutes % 60

# Display result
print ( " Hours : " , hours )
print ( " Minutes : " , remain ing_m inutes )

Example Output
Enter number of minutes: 125
Hours: 2
Minutes: 5

m
co
Example Program 4
fli x
Question 4: Write a program to convert total number of months into years and months.
ad fli
Python Program
x.
ac ad

# Ask user to enter total number of months


total_months = int ( input ( " Enter total number of months : " ))
w. Ac

# Calculate number of years


years = total_months // 12

# Calculate remaining months


remaining_months = total_months % 12

# Display result
print ( " Years : " , years )
print ( " Months : " , remaining_months )
ww

Example Output
Enter total number of months: 38
Years: 3
Months: 2

Example Program 5
Question 5: Write a program that repeatedly asks the user to enter numbers. The user
can type ’done’ to stop. The program should print the sum of all numbers entered.
Python Program
# Initialize total sum to 0
total = 0

# Ask the user for input


s = input ( ’ Enter a number or " done ": ’)

# Loop until user types ’ done ’


while s != ’ done ’:
num = int ( s )
total = total + num

om
s = input ( ’ Enter a number or " done ": ’)

# After loop , print the sum


print ( ’ The sum of entered numbers is ’ , total )

.c
ix x
Explanation fl li
This program lets the user enter as many numbers as they like. Each time the user types
a number, that number is added to the total sum.
When the user types the word ’done’, the loop stops, and the program prints the
final sum of all the numbers entered.
ad df
This is called a “sentinel-controlled loop” — we are using the word ’done’ as a signal
to stop the loop.
ac ca

Example Run
Enter a number or "done": 5
Enter a number or "done": 7
w. A

Enter a number or "done": 12


Enter a number or "done": done
The sum of entered numbers is 24

Example Program 6
Question 6: Fill in the missing lines of code. The program reads a limit value and then
reads prices. It prints the largest price that is less than the limit. The program stops
ww

when the user enters 0.

Completed Python Program


# Read the limit
limit = float ( input ( " Enter the limit : " ))

# Initialize max_price
max_price = 0
# Read the next price
next_price = float ( input ( " Enter a price or 0 to stop : " ))

# Loop while price is not 0


while next_price > 0:
# Check if price is less than limit and greater than current max_price
if next_price < limit and next_price > max_price :
max_price = next_price

# Read the next price


next_price = float ( input ( " Enter a price or 0 to stop : " ))

om
# After loop , print result
if max_price > 0:
print ( " The largest price below the limit is : " , max_price )
else :

.c
print ( " No price was below the limit . " )

ix x
Explanation
fl li
This program helps you find the biggest price that is smaller than a given limit.
The program first asks the user for a limit value. Then it asks the user to enter prices
one by one. If a price is less than the limit, and bigger than all previous prices, it is saved
ad df
as the new “max price”.
The loop stops when the user enters 0. At the end, the program prints the largest
price found.
ac ca

Example Run
Enter the limit: 100
w. A

Enter a price or 0 to stop: 45


Enter a price or 0 to stop: 75
Enter a price or 0 to stop: 120
Enter a price or 0 to stop: 80
Enter a price or 0 to stop: 0
The largest price below the limit is: 80

Question : Find the output of the following Python Code snippets.


ww

# (a)
count = 0
while count < 10:
print ( ’ Hello ’)
count += 1
# Output : ’ Hello ’ will be printed 10 times

# (b)
x = 10
y = 0
while x > y :
print (x , y )
x = x - 1
y = y + 1
# Output :
# (10 0)
# (9 1)
# (8 2)
# (7 3)
# (6 4)
# (5 5)

# (c)

om
keepgoing = True
x = 100
while keepgoing :
print ( x )

.c
x = x - 10
if x < 50:

ix x
keepgoing = False
# Output :
# 100
# 90
fl li
# 80
# 70
ad df
# 60
# 50

# (d)
ac ca

x = 45
while x < 50:
print ( x )
x = x + 1
w. A

# Output :
# 45
# 46
# 47
# 48
# 49

# (e)
ww

for x in [1 ,2 ,3 ,4 ,5]:
print ( x )
# Output :
# 1 2 3 4 5

# (f)
for p in range (1 ,10):
print ( p )
# Output : 1 2 3 4 5 6 7 8 9

# (g)
for z in range ( -500 ,500 ,100):
print ( z )
# Output :
# -500
# -400
# -300
# -200
# -100
# 0
# 100
# 200
# 300

om
# 400

# (h)
x = 10

.c
y = 5
for i in range ( x - y * 2):

ix x
print ( " % " , i )
# Output : No output , range will be range (0) , so empty loop

# (i)
fl li
c = 0
for x in range (10):
ad df
for y in range (5):
c += 1
print ( c )
# Output : 50
ac ca

# (j)
x = [1 ,2 ,3]
counter = 0
w. A

while counter < len ( x ):


print ( x [ counter ] * ’% ’)
for y in x :
print ( y * ’* ’)
counter += 1
# Output :
# % ( one %)
# 1 stars , 2 stars , 3 stars
ww

# %% ( two %)
# 1 stars , 2 stars , 3 stars
# %%% ( three %)
# 1 stars , 2 stars , 3 stars

# (k)
for x in ’ lamp ’:
print ( str . upper ( x ))
# Output :
# L
# A
# M
# P

# (l)
x = ’ one ’
y = ’ two ’
counter = 0
while counter < len ( x ):
print ( x [ counter ] , y [ counter ])
counter += 1
# Output :
# o t

om
# n w
# e o

# (m)

.c
x = " apple , pear , peach "
y = x . split ( " , " )

ix x
for z in y :
print ( z )
# Output :
# apple
fl li
# pear
# peach
ad df
# (n)
x = ’ apple , pear , peach , grapefruit ’
y = x . split ( ’ , ’)
ac ca

for z in y :
if z < ’m ’:
print ( str . lower ( z ))
else :
w. A

print ( str . upper ( z ))


# Output :
# apple
# PEAR
# PEACH
# grapefruit

# Read an integer N from the user


ww

N = int ( input ( " Enter an integer N : " ))

# Determine start and end points based on whether N is nonnegative or negativ


if N >= 0:
start = N
end = 2 * N
else :
start = 2 * N
end = N

# Initialize sum
total = 0

# Loop from start to end ( inclusive ) and add to total


for i in range ( start , end + 1):
total += i

# Display the result


print ( " The sum from " , start , " to " , end , " is " , total )

# Question :
# Write a program that reads an integer N from the user and prints

om
the sum of the integers
# from N to 2 N if N is nonnegative , or from 2 N to N if N is negative .

# Program :

.c
# Read an integer N from the user

ix x
N = int ( input ( " Enter an integer N : " ))
fl li
# Determine start and end points based on whether N is

nonnegative or negative
if N >= 0:
ad df
start = N
end = 2 * N
else :
start = 2 * N
ac ca

end = N

# Initialize sum
total = 0
w. A

# Loop from start to end ( inclusive ) and add to total


for i in range ( start , end + 1):
total += i

# Display the result


print ( " The sum from " , start , " to " , end , " is " , total )

# Explanation :
ww

# If N >= 0 then sum numbers from N to 2 N


# If N < 0 then sum numbers from 2 N to N
# The loop range includes both start and end
# The program prints the total sum after the loop

# Example Run 1:
# Enter an integer N : 3
# The sum from 3 to 6 is 18
# (3 + 4 + 5 + 6 = 18)

# Example Run 2:
# Enter an integer N : -2
# The sum from -4 to -2 is -9
# ( -4 + -3 + -2 = -9)

Question 5:
Write a program as follows:

Inp = input("Please enter a string: ")


while len(Inp) <= 4:
if Inp[-1] == ’z’: # condition 1
Inp = Inp[0:3] + ’c’
elif ’a’ in Inp: # condition 2

om
Inp = Inp[0] + ’bb’
elif not int(Inp[0]): # condition 3
Inp = ’1’ + Inp[1:] + ’z’
else:

.c
Inp = Inp + ’*’

ix x
print(Inp)

Explanation:
fl li
The program reads a string and enters a while loop which runs as long as the length
of the string is 4 or less. Inside the loop:
ad df
- If the last character is ’z’, it replaces the last character with ’c’. - If the string
contains ’a’, it replaces the string with first character + ’bb’. - If the first character
cannot be converted to integer, it changes first character to ’1’ and adds ’z’ at the end.
- Otherwise, it appends ’*’ to the string.
ac ca

The loop continues until the string length exceeds 4, after which it prints the final
string.
Example Runs:
w. A

Input: ’1bzz’
Iteration 1: ’1bzz’ → condition 1 → becomes ’1bzc’
Iteration 2: ’1bzc’ → else → becomes ’1bzc*’ → length exceeds 4 → Output: 1bzc*
Input: ’1a’
Iteration 1: ’1a’ → condition 2 → becomes ’1bb’
Iteration 2: ’1bb’ → else → ’1bb*’
Iteration 3: ’1bb*’ → else → ’1bb**’ → length exceeds 4 → Output: 1bb**
Input: ’abc’
Condition 2 keeps applying repeatedly → Endless loop.
ww

Input: ’0xy’
No error from int(’0’). Proceeds to append ’*’ until done. Final: 1xyc*
Input: ’xyz’
int(’x’) raises ValueError - program crashes with an error.

Palindrome Question:
Write a program that reads a string and checks whether it is a palindrome string or not.

string = input("Enter a string: ")


length = len(string)
mid = length // 2
rev = -1

for a in range(mid):
if string[a] == string[rev]:
rev -= 1
else:
print(string, "is not a palindrome")
break
else:
print(string, "is a palindrome")

Explanation:
A palindrome is a string that reads the same forwards and backwards. This program

m
compares each character in the first half of the string with the corresponding character
from the end.

co
If all pairs match, it prints ”is a palindrome”. If any pair does not match, it prints
”is not a palindrome” and stops.

fli x
Example Runs:
ad fli
x.
Input: ’madam’
Comparisons: ’m’ vs ’m’, ’a’ vs ’a’, ’d’ vs ’d’ — all match → Output: madam is a
palindrome
ac ad

Input: ’hello’
First comparison ’h’ vs ’o’ → mismatch → Output: hello is not a palindrome
Question:
w. Ac

What will be the output of the following code snippet?

Lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Lst[::2] = 10, 20, 30, 40, 50, 60
print(Lst)

Options:
(a) ValueError: attempt to assign sequence of size 6 to extended slice of size 5
(b) [10, 2, 20, 4, 30, 6, 40, 8, 50, 60]
(c) [1, 2, 10, 20, 30, 40, 50, 60]
ww

(d) [1, 10, 3, 20, 5, 30, 7, 40, 9, 50, 60]


Explanation:
The slice Lst[::2] selects every second element from the list, starting from index 0.
For the list [1, 2, 3, 4, 5, 6, 7, 8, 9], this selects:
[1, 3, 5, 7, 9] → a slice of size 5.
Now we are trying to assign a sequence of size 6:
(10, 20, 30, 40, 50, 60)
Since the sizes do not match (cannot assign 6 values to 5 positions), Python will raise
a ValueError.
Correct Answer: (a) ValueError
Summary:
- Lst[::2] selects 5 positions. - Trying to assign 6 values causes a mismatch. -
Python raises an error immediately, no assignment is done.
Question:
What will be the output of the following code snippet?

dc1 = {}
dc1[1] = 1
dc1[’1’] = 2
dc1[1.0] = 4

sum = 0
for k in dc1:

om
sum += dc1[k]

print(sum)

.c
Explanation:

ix x
The dictionary dc1 is being updated with three different keys:
fl li
• dc1[1] = 1 → adds key 1 with value 1.
• dc1[’1’] = 2 → adds key ’1’ (string) with value 2.
ad df
• dc1[1.0] = 4 → note that 1.0 is treated as equal to 1 in dictionary keys.

In Python, 1 and 1.0 are considered the same key because:


ac ca

hash(1) == hash(1.0) and 1 == 1.0


So, dc1[1.0] = 4 will overwrite the earlier dc1[1] = 1.
Final dictionary contents:
w. A

{ 1: 4, ’1’: 2 }

Now, the for loop iterates over keys 1 and ’1’:

• sum += dc1[1] → sum becomes 4.


• sum += dc1[’1’] → sum becomes 4 + 2 = 6.

Final Output:
ww

Summary:
- Python treats 1 and 1.0 as the same key. - The final dictionary has two keys: 1 and
’1’. - The sum of values is 4 + 2 = 6. - Correct answer: 6.
Type B : Application Based Questions

1. What will be the output produced by the following code fragments?


(a)
y = str(123)
x = "hello" * 3
print(x, y)

x = "hello" + "world"
y = len(x)
print(y, x)

(b)

x = "hello" + "to Python" + "world"


for char in x:

om
y = char
print(y, ’-’, end = ’ ’)

.c
(c)

ix x
x = "hello world"
fl li
print(x[:2], x[:-2], x[-2:])
print(x[6], x[2:4])
print(x[2:-3], x[-4:-2])
ad df
2. Write a short Python code segment that adds up the lengths of all the
words in a list and then prints the average (mean) length. Use the final list
from previous question to test your program.
ac ca

words = ["hello", "world", "python", "programming"]


total_length = 0
w. A

for word in words:


total_length += len(word)
average_length = total_length / len(words)
print("Average word length:", average_length)

3. Predict the output of the following code snippet:

a = [1, 2, 3, 4, 5]
ww

print(a[3:0:-1])

4. Predict the output of the following code snippet:


(a)

arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = " ")
(b)

Numbers = [9, 18, 27, 36]


for Num in Numbers:
for N in range(1, Num % 8):
print(N, "#", end = " ")
print()

5. Find the errors. State reasons.


(a)

om
t = (1, "a", 9.2)
t[0] = 6

Reason: Tuples are immutable. Cannot assign to an element of a tuple.

.c
(b)

ix x
fl li
t = [1, "a", 9.2]
t[0] = 6

Reason: No error. Lists are mutable. Assignment is valid.


ad df
(c)

t = [1, "a", 9.2]


t[4] = 6
ac ca

Reason: IndexError: list assignment index out of range. List has only 3 elements
(indexes 0 to 2).
w. A

(d)

t = ’hello’
t[0] = ’H’

Reason: Strings are immutable. Cannot assign to string index.


(e)
ww

for Name in [Amar, Shveta, Parag]:


if Name[0] == ’S’:
print(Name)

Reason: The names Amar, Shveta, Parag are not defined as strings (missing quotes).
Should be:

for Name in ["Amar", "Shveta", "Parag"]:


if Name[0] == ’S’:
print(Name)
[CBSE D 2016]

Question:
Trace the following code and predict the output produced by it.

def power(b, p):


y = b ** p
return y

def calcSquare(x):
a = power(x, 2)
return a

n = 5

m
result = calcSquare(n) + power(3, 3)
print(result)

co
Explanation:

fli x
We have two functions defined:
1. power(b, p) computes bp and returns the result. 2. calcSquare(x) calls power(x,
ad fli
x.
2), which means it computes x2 .
Now step by step:
ac ad
Step 1: n = 5
Step 2: calcSquare(n)
This calls power(5, 2):
52 = 25
w. Ac

So calcSquare(5) returns 25.


Step 3: power(3, 3)

33 = 27
So power(3, 3) returns 27.
Step 4: Final calculation:

result = 25 + 27 = 52
ww

Final Output:

52

Summary:
- calcSquare(5) returns 25 - power(3, 3) returns 27 - Total result is 52.
Question:
What is the difference between the formal parameters and actual parameters? What
are their alternative names? Also, give a suitable Python code to illustrate both.
Answer:
Actual Parameter: An actual parameter is the value that is passed to a function
when the function is called. It appears in the function call statement. It is also known
as an Argument.
Formal Parameter: A formal parameter is the variable that is used in the function
definition (function header) to receive the value from the actual parameter. It appears
in the function definition. It is also known as a Parameter.
Example:

def addEm(x, y, z):


print(x + y + z)

addEm(6, 16, 26)

m
Explanation:
In the above code:
- 6, 16, and 26 are the actual parameters (arguments). These are the values

co
provided when calling the function.

fli x
- x, y, and z are the formal parameters (parameters). These are the variable names
used inside the function definition to receive the values.
ad fli
Output:
x.
ac ad
48

Summary:
w. Ac

- Actual parameters are given in the function call. - Formal parameters are
defined in the function header.
Question 8:
What will the following code print?

def addEm(x, y, z):


print(x + y + z)

def prod(x, y, z):


return x * y * z
ww

a = addEm(6, 16, 26)


b = prod(2, 3, 6)

print(a, b)

Explanation:
Step by step:
Step 1: Function addEm(6, 16, 26) is called.

• Inside addEm, it prints 6 + 16 + 26 = 48.

• But addEm does not have a return statement, so it returns None.


• Therefore, variable a gets assigned None.

Step 2: Function prod(2, 3, 6) is called.

• It returns 2 ∗ 3 ∗ 6 = 36.

• So variable b gets assigned value 36.

Step 3: The final print(a, b) prints:

None 36

Final Output:

m
48
None 36

co
Summary:
fli x
- addEm prints 48, but returns None. - prod returns 36. - The final print shows: None
ad fli
36.
Question 16:
x.
Predict the output of the following code fragment.
ac ad

def check(n1 = 1, n2 = 2):


n1 = n1 + n2
w. Ac

n2 += 1
print(n1, n2)

check()
check(2, 1)
check(3)

Explanation:
First call: check()
ww

Defaults: n1 = 1, n2 = 2

• n1 = 1 + 2 = 3

• n2 = 2 + 1 = 3

• Output: 3 3

Second call: check(2, 1)

• n1 = 2 + 1 = 3

• n2 = 1 + 1 = 2

• Output: 3 2
Third call: check(3)
Defaults: n2 = 2

• n1 = 3 + 2 = 5

• n2 = 2 + 1 = 3

• Output: 5 3

Final Output:

3 3
3 2
5 3

m

co
Question 17:
What is the output of the following code?

fli x
ad fli
x.
a = 1

def f():
ac ad
a = 10

print(a)
w. Ac

Explanation:
The function f() is defined but never called. Therefore, the global variable a = 1 is
printed.
Final Output:


ww

Question 18:
What will be the output of the following code?

def interest(prnc, time = 2, rate = 0.10):


return (prnc * time * rate)

print(interest(6100, 1))
print(interest(5000, rate = 0.05))
print(interest(5000, 3, 0.12))
print(interest(time = 4, prnc = 5000))
Explanation:
First call: interest(6100, 1)

6100 ∗ 1 ∗ 0.10 = 610.0

Second call: interest(5000, rate = 0.05)

5000 ∗ 2 ∗ 0.05 = 500.0

Third call: interest(5000, 3, 0.12)

5000 ∗ 3 ∗ 0.12 = 1800.0

Fourth call: interest(time = 4, prnc = 5000)

om
5000 ∗ 4 ∗ 0.10 = 2000.0

.c
Final Output:

ix x
610.0
500.0
1800.0
fl li
2000.0

Question:
ad df
What is the output of the following code fragments?
Part (i):
ac ca

def increment(n):
n.append([4])
return n
w. A

L = [1, 2, 3]
M = increment(L)
print(L, M)

Explanation:
In Python, lists are mutable and are passed by reference. The function increment(n)
appends [4] to the list n.
L and M both refer to the same list object.
ww

Step by step:
- Initial L = [1, 2, 3] - After calling increment(L), L becomes [1, 2, 3, [4]] - M is also
pointing to this same list.
Final Output:

[1, 2, 3, [4]] [1, 2, 3, [4]]

Part (ii):
def increment(n):
n.append([49])
return n[0], n[1], n[2], n[3]

L = [23, 35, 47]


m1, m2, m3, m4 = increment(L)
print(L)
print(m1, m2, m3, m4)
print(L[3] == m4)

Explanation:
Again, L is a list. Lists are mutable.
Step by step:
1. Initial L = [23, 35, 47] 2. Function increment(L) is called. - L.append([49])

m
appends a new list [49] to L. - Now L becomes: [23, 35, 47, [49]] - The function returns:
n[0], n[1], n[2], n[3] which are: 23, 35, 47, [49]

co
Assignments:
- m1 = 23 - m2 = 35 - m3 = 47 - m4 = [49]
Finally:
fli x
ad fli
- print(L) prints: [23, 35, 47, [49]] - print(m1, m2, m3, m4) prints: 23 35 47 [49] -

x.
print(L[3] == m4) evaluates to: True because m4 and L[3] both refer to the same list
object [49].
ac ad

Final Output:

[23, 35, 47, [49]]


w. Ac

23 35 47 [49]
True

Question:

(1) Write a function that receives two numbers and generates a random number from
that range. Using this function, the main program should be able to print three numbers
randomly.
(2) Write a function that receives two string arguments and checks whether they are
same-length strings (returns True in this case, otherwise False).
ww


Answer 1:

import random

def generate_random(start, end):


return random.randint(start, end)

# Main program
print("Three random numbers:")
print(generate_random(10, 50))
print(generate_random(10, 50))
print(generate_random(10, 50))

Explanation:
We use the random module.
Function generate random(start, end) generates a random integer between start and end
The main program calls this function three times to print three random numbers.

Answer 2:

def same_length(str1, str2):

om
if len(str1) == len(str2):
return True
else:
return False

.c
ix x
# Example usage:
print(same_length("hello", "world")) # True
fl li
print(same_length("python", "code")) # False

Explanation:
ad df
Function same length(str1, str2) checks if the lengths of two strings are equal.
It returns True if they are of the same length, otherwise it returns False.
Example calls are shown for clarity.
Question 5:
ac ca

Write a function stats() that accepts a filename and reports the file’s longest line.
Solution:
w. A

def stats(filename):
longest = ""
for line in open(filename):
if len(line) > len(longest):
longest = line
print("Longest line’s length =", len(longest))
print(longest)

Explanation:
ww

- The function stats(filename) takes a file name as input. - It reads the file line by
line. - It keeps track of the longest line seen so far. - At the end, it prints the length of
the longest line and the line itself.
Important points:
- The file is opened using open(filename). - The loop iterates over each line. -
longest stores the current longest line. - The comparison is done using len(line).

Question 6:
What is the output of the following code fragment? Explain.
out = open("output.txt", "w")
out.write("Hello, world!\n")
out.write("How are you?")
out.close()

open("output.txt").read()

Explanation:
Step by step:
1. The file output.txt is opened in write mode "w". 2. First line written: "Hello,
world!\n"
This writes: Hello, world! and moves to next line. 3. Second line written: "How are
you?"
This writes: How are you? on the next line. 4. The file is closed using out.close(). 5.

m
The file is reopened and read using open("output.txt").read().
Final Output:

co
Hello, world!
How are you?
fli x
ad fli
Summary:

x.
- The first line ends with a newline character \n, so ”How are you?” is printed on a
ac ad
new line. - The file output.txt now contains two lines.
Sorting Algorithms: Write the Algorithm and Python Program for the
following sorting techniques. Also explain with suitable examples.

w. Ac

Question 1: Bubble Sort


Algorithm:

• Compare adjacent elements and swap if out of order.


• Repeat for all elements until list is sorted.

Python Program:

def bubble_sort(arr):
ww

n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]

arr = [64, 34, 25, 12, 22, 11, 90]


bubble_sort(arr)
print("Sorted array:", arr)


Question 2: Insertion Sort
Algorithm:
• Build sorted array one item at a time by inserting element into correct position.

Python Program:

def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

om
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print("Sorted array:", arr)

.c
ix x

Question 3: Selection Sort
fl li
Algorithm:

• Find minimum element and move it to sorted portion.


ad df
Python Program:

def selection_sort(arr):
ac ca

for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
w. A

min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]

arr = [64, 25, 12, 22, 11]


selection_sort(arr)
print("Sorted array:", arr)


Question 4: Quick Sort
ww

Algorithm:

• Select pivot, partition array into two subarrays, recursively sort.

Python Program:

def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
less = [x for x in arr[1:] if x <= pivot]
greater = [x for x in arr[1:] if x > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)

arr = [10, 7, 8, 9, 1, 5]
arr = quick_sort(arr)
print("Sorted array:", arr)


Question 5: Heap Sort
Algorithm:

om
• Build max heap, extract maximum one by one.

Python Program:

.c
ix x
def heapify(arr, n, i):
largest = i
l = 2*i + 1
fl li
r = 2*i + 2
if l < n and arr[l] > arr[largest]:
ad df
largest = l
if r < n and arr[r] > arr[largest]:
largest = r
if largest != i:
ac ca

arr[i], arr[largest] = arr[largest], arr[i]


heapify(arr, n, largest)

def heap_sort(arr):
w. A

n = len(arr)
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)

arr = [12, 11, 13, 5, 6, 7]


ww

heap_sort(arr)
print("Sorted array:", arr)


Question 6: Merge Sort
Algorithm:

• Divide array into halves, recursively sort and merge.

Python Program:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]

merge_sort(L)
merge_sort(R)

i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:

om
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]

.c
j += 1

ix x
k += 1
fl li
while i < len(L):
arr[k] = L[i]
i += 1
ad df
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
ac ca

k += 1

arr = [12, 11, 13, 5, 6, 7]


merge_sort(arr)
w. A

print("Sorted array:", arr)


Searching Algorithms: Write the Algorithm and Python Program for the
following searching techniques. Also explain with suitable examples.

Question 7: Linear Search
Algorithm:
ww

• Traverse the list and compare each element with target.

Python Program:

def linear_search(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = [10, 20, 30, 40, 50]
x = 30
result = linear_search(arr, x)
print("Element found at index:", result)


Question 8: Binary Search
Algorithm:

• Works only on sorted array.

• Repeatedly divide search space by half.

Python Program:

m
def binary_search(arr, x):
low = 0

co
high = len(arr) - 1
while low <= high:

fli x
mid = (low + high) // 2
if arr[mid] == x:
ad fli
x.
return mid
elif arr[mid] < x:
ac ad
low = mid + 1
else:
high = mid - 1
return -1
w. Ac

arr = [10, 20, 30, 40, 50]


x = 30
result = binary_search(arr, x)
print("Element found at index:", result)


Connecting Python with SQL: Questions and Answers

ww

Question 1: What are the main steps involved in creating a database connectivity
application in Python? Explain briefly.
Answer: There are 7 main steps:
1. Start Python.

2. Import the required database package (such as sqlite3 or mysql.connector).

3. Open a connection to the database.

4. Create a cursor instance.

5. Execute a query.

6. Extract data from the result set.


7. Clean up the environment (close cursor and connection).


Question 2: Write a Python program to connect to an SQLite database and display
all records from a table called Students.
Answer:

import sqlite3

# Step 1: Connect to database (creates file if not exists)


conn = sqlite3.connect(’school.db’)

om
# Step 2: Create cursor
cur = conn.cursor()

# Step 3: Execute SELECT query

.c
cur.execute("SELECT * FROM Students")

ix x
# Step 4: Fetch and display results
fl li
rows = cur.fetchall()
for row in rows:
print(row)
ad df
# Step 5: Close cursor and connection
cur.close()
conn.close()
ac ca


Question 3: How do you insert a record into a table using Python? Write an example
using MySQL.
w. A

Answer:

import mysql.connector

# Connect to MySQL database


conn = mysql.connector.connect(
host="localhost",
user="root",
ww

password="password",
database="school"
)

# Create cursor
cur = conn.cursor()

# Execute INSERT query


sql = "INSERT INTO Students (rollno, name, marks) VALUES (%s, %s, %s)"
values = (101, "Alice", 85)
cur.execute(sql, values)

# Commit the transaction


conn.commit()

# Close cursor and connection


cur.close()
conn.close()

Question 4: Why is it important to close the cursor and connection after completing
the database operations? Explain.

om
Answer: It is important to close the cursor and connection to:
• Release the database resources.
• Prevent memory leaks.

.c
ix x
• Avoid locking database tables unnecessarily.
fl li
• Ensure proper transaction handling and avoid accidental data corruption.

Question 5: Write a Python program that updates marks of a student in the
ad df
Students table.
Answer:
import sqlite3
ac ca

# Connect to database
conn = sqlite3.connect(’school.db’)
cur = conn.cursor()
w. A

# Update marks
sql = "UPDATE Students SET marks = ? WHERE rollno = ?"
values = (95, 101)
cur.execute(sql, values)

# Commit changes
conn.commit()
ww

# Close connection
cur.close()
conn.close()
Python Programming: Questions and Answers on Patterns, Series, Facto-
rial, etc.

Question 1: Write a Python program to print a simple right-angled triangle pattern
of stars.
Answer:
n = 5
for i in range(1, n+1):
print("*" * i)

Explanation: This prints rows of stars from 1 to n.



Question 2: Write a Python program to print an inverted right-angled triangle
pattern.
Answer:

n = 5
for i in range(n, 0, -1):

om
print("*" * i)

Explanation: We use reverse loop to print decreasing stars.


.c
Question 3: Write a Python program to find the factorial of a positive number.

ix x
Answer:
fl li
num = int(input("Enter a positive number: "))
factorial = 1
for i in range(1, num+1):
factorial *= i
ad df
print("Factorial of", num, "is", factorial)

Explanation: Factorial of n is n! = 1 * 2 * ... * n.



ac ca

Question 4: Write a Python program to calculate the sum of first n natural numbers.
Answer:
w. A

n = int(input("Enter value of n: "))


sum_n = 0
for i in range(1, n+1):
sum_n += i
print("Sum of first", n, "natural numbers is", sum_n)

Explanation: We add numbers from 1 to n.



Question 5: Write a program to calculate sum of the series: 1 + 1/2 + 1/3 + ... +
ww

1/n.
Answer:

n = int(input("Enter value of n: "))


sum_series = 0.0
for i in range(1, n+1):
sum_series += 1/i
print("Sum of series is", sum_series)
Explanation: This is the harmonic series.

Question 6: Write a program to print Fibonacci series up to n terms.
Answer:

n = int(input("Enter number of terms: "))


a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

Explanation: Fibonacci series: 0, 1, 1, 2, 3, 5, 8, ...


om
Question 7: Write a program to print multiplication table of a given number.
Answer:

num = int(input("Enter number: "))

.c
for i in range(1, 11):

ix x
print(f"{num} x {i} = {num * i}")
fl li
Explanation: Prints table from 1 to 10.

Question 8: Write a program to print this pattern:
ad df
1
1 2
1 2 3
...
ac ca

Answer:

n = 5
w. A

for i in range(1, n+1):


for j in range(1, i+1):
print(j, end=" ")
print()

Explanation: Nested loop for row and column.



Question 9: Write a program to check if a number is a palindrome.
Answer:
ww

num = input("Enter a number: ")


if num == num[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

Explanation: We check if reverse of string equals original.



Question 10: Write a program to calculate sum of squares of first n natural numbers.
Answer:
n = int(input("Enter value of n: "))
sum_squares = 0
for i in range(1, n+1):
sum_squares += i * i
print("Sum of squares:", sum_squares)

Explanation: Sum of squares: 12 + 22 + ... + n2 .

m
co
fli x
ad fli
x.
ac ad
w. Ac
ww

You might also like