Python Important Programs
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 remaining seconds after taking out the full minutes
w. A
The user enters any number of seconds. For example, if the user types 135 seconds:
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
Example Output
w. A
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 : " ))
# 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
# 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
om
s = input ( ’ Enter a number or " done ": ’)
.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
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
# Initialize max_price
max_price = 0
# 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
# (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
# %% ( 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
# Initialize sum
total = 0
# 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
# Explanation :
ww
# 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:
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.
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
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
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.
{ 1: 4, ’1’: 2 }
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
x = "hello" + "world"
y = len(x)
print(y, x)
(b)
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
a = [1, 2, 3, 4, 5]
ww
print(a[3:0:-1])
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)
om
t = (1, "a", 9.2)
t[0] = 6
.c
(b)
ix x
fl li
t = [1, "a", 9.2]
t[0] = 6
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: The names Amar, Shveta, Parag are not defined as strings (missing quotes).
Should be:
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
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:
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?
print(a, b)
Explanation:
Step by step:
Step 1: Function addEm(6, 16, 26) is called.
• It returns 2 ∗ 3 ∗ 6 = 36.
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
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
• 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?
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)
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:
Part (ii):
def increment(n):
n.append([49])
return n[0], n[1], n[2], n[3]
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]
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
# 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:
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
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]
—
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:
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]
—
Question 4: Quick Sort
ww
Algorithm:
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
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)
heap_sort(arr)
print("Sorted array:", arr)
—
Question 6: Merge Sort
Algorithm:
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
—
Searching Algorithms: Write the Algorithm and Python Program for the
following searching techniques. Also explain with suitable examples.
—
Question 7: Linear Search
Algorithm:
ww
Python Program:
—
Question 8: Binary Search
Algorithm:
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
—
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.
5. Execute a query.
—
Question 2: Write a Python program to connect to an SQLite database and display
all records from a table called Students.
Answer:
import sqlite3
om
# Step 2: Create cursor
cur = conn.cursor()
.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
password="password",
database="school"
)
# Create cursor
cur = conn.cursor()
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)
n = 5
for i in range(n, 0, -1):
om
print("*" * i)
.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)
Question 4: Write a Python program to calculate the sum of first n natural numbers.
Answer:
w. A
1/n.
Answer:
om
Question 7: Write a program to print multiplication table of a given number.
Answer:
.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
m
co
fli x
ad fli
x.
ac ad
w. Ac
ww