Hello everyone, if you are currently pursuing the NIELIT O Level Computer course, this post is dedicated to O Level Python Practical Questions. In this article, we have compiled a list of Python Practical Previous Year Questions that could prove crucial for your upcoming exams. Therefore, we encourage you to take some time to go through these questions and practice solving them. We have included the top 20 Python Practical Questions to help you in your preparation. Let’s dive in!
O Level Python Practical Questions
Accept the name of the laborer and no. of hours worked. Calculate and display the wages. The program should run for N number of laborer’s as specified by the user.
Question 1. Accept the name of the laborer and no. of hours worked. Calculate and display the wages. The program should run for N number of laborer’s as specified by the user.
Solution:
# Function to calculate wages
def calculate_wages(hours_worked, hourly_rate):
return hours_worked * hourly_rate
try:
# Get the number of laborers from the user
N = int(input("Enter the number of laborers: "))
# Initialize an empty list to store laborer names and wages
laborers = []
# Get information for each laborer
for i in range(N):
name = input(f"Enter the name of laborer {i+1}: ")
hours_worked = float(input(f"Enter the number of hours worked by {name}: "))
hourly_rate = float(input(f"Enter the hourly rate for {name}: "))
# Calculate wages
wages = calculate_wages(hours_worked, hourly_rate)
# Append the name and wages to the list
laborers.append((name, wages))
# Display the wages for each laborer
print("\nWages for each laborer:")
for name, wages in laborers:
print(f"{name}: ${wages:.2f}")
except ValueError:
print("Invalid input. Please enter valid numbers for hours worked and hourly rate.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Question 2. Write a program to print all Armstrong numbers in a given range. Note: An Armstrong number is a number whose sum of cubes of digits is equal to the number itself. E.g. 370=33+73+03
Solution:
s=int(input("Input start number : "))
e=int(input("Input end number : "))
for i in range(s,e+1):
num=i
temp = num
sum = 0
while num>0:
rem = num%10
sum = sum+(rem**3)
num = num//10
if temp == sum:
print(temp," ")
Question 3. Write a program to multiply two numbers by repeated addition e.g. 6*7 = 6+6+6+6+6+6+6
Solution:
num1=int(input("Enter first number "))
num2=int(input("Enter second number "))
product=0
for i in range (1,num2+1):
product=product+num1
print("The multiply is: ",product)
Question 4. Write a Python function that takes a string as parameter and returns a string with every successive repetitive character replaced by & e.g. Parameter may become Par&met&r.
Solution:
def replace_repetitive_characters(input_string):
result = []
for char in input_string:
if not result or char != result[-1]:
result.append(char)
else:
result.append('&')
return ''.join(result)
# Example usage:
input_str = "Parameter"
result_str = replace_repetitive_characters(input_str)
print(result_str) # Output: "Par&met&r"
Question 5. Write a Python function to find the sum of all numbers between 100 and 500 which are divisible by 2.
Solution:
def numbers(start, end):
total = 0
for num in range(start, end + 1):
if num % 2 == 0:
total += num
return total
# Example usage:
start_num = 100
end_num = 500
result_sum = numbers(start_num, end_num)
print(f"Sum of even numbers between {start_num} and {end_num}: {result_sum}")
Question 6. Write a Python function to get two matrices and multiply them. Make sure that number of columns of first matrix = number of rows of second.
Solution:
def multiply_matrices(matrix1, matrix2):
rows1 = len(matrix1)
cols1 = len(matrix1[0])
rows2 = len(matrix2)
cols2 = len(matrix2[0])
if cols1 != rows2:
return "Matrix multiplication is not possible. The number of columns in the first matrix must be equal to the number of rows in the second matrix."
result = [[0 for _ in range(cols2)] for _ in range(rows1)]
for i in range(rows1):
for j in range(cols2):
for k in range(rows2):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
# Example usage:
matrix1 = [
[1, 2],
[3, 4]
]
matrix2 = [
[5, 6],
[7, 8]
]
result_matrix = multiply_matrices(matrix1, matrix2)
if isinstance(result_matrix, str):
print(result_matrix) # Matrix multiplication is not possible.
else:
for row in result_matrix:
print(row)
Question 7. Write a Python function which takes list of integers as input and finds:
(a) The largest positive number in the list
(b) The smallest negative number in the list
(c) Sum of all positive numbers in the list
def analyze_numbers(numbers):
largest_positive = None
smallest_negative = None
sum_of_positives = 0
for num in numbers:
if num > 0:
if largest_positive is None or num > largest_positive:
largest_positive = num
sum_of_positives += num
elif num < 0:
if smallest_negative is None or num < smallest_negative:
smallest_negative = num
return largest_positive, smallest_negative, sum_of_positives
# Example usage:
number_list = [5, -2, 9, -7, 1, 0, -3]
largest_pos, smallest_neg, sum_positives = analyze_numbers(number_list)
print(f"Largest positive number: {largest_pos}")
print(f"Smallest negative number: {smallest_neg}")
print(f"Sum of positive numbers: {sum_positives}")
Question 8. Write a Python program to print all the prime numbers in the given range. an Interval. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Solution:
def is_prime(number):
if number <= 1:
return False
if number <= 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False
i = 5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
def print_primes_in_range(start, end):
for num in range(start, end + 1):
if is_prime(num):
print(num)
# Example usage:
start_range = 10
end_range = 50
print(f"Prime numbers between {start_range} and {end_range}:")
print_primes_in_range(start_range, end_range)
Question 9: Write a Python program to print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term. N is the value given by the user.
Solution:
def sum_of_series(n):
if n <= 0:
return 0
series_sum = 0
for i in range(1, n + 1):
term = i**3
series_sum += term
return series_sum
try:
n = int(input("Enter the value of n: "))
if n < 0:
print("Please enter a positive value for n.")
else:
result = sum_of_series(n)
print(f"The sum of the series is: {result}")
Question 10. Write a Python Program to find the successor and predecessor of the largest element in an array.
Solution:
def find_successor_predecessor(arr):
if not arr:
return None, None
max_element = arr[0]
successor = None
predecessor = None
for num in arr:
if num > max_element:
max_element = num
for num in arr:
if num == max_element:
continue
if num < max_element and (predecessor is None or num > predecessor):
predecessor = num
if num > max_element and (successor is None or num < successor):
successor = num
return predecessor, successor
# Example usage:
input_array = [12, 8, 18, 24, 7, 31, 45, 29]
predecessor, successor = find_successor_predecessor(input_array)
if predecessor is not None:
print(f"Predecessor of the largest element is: {predecessor}")
else:
print("No predecessor found.")
if successor is not None:
print(f"Successor of the largest element is: {successor}")
else:
print("No successor found.")
Question 11. Write a Python program that takes list of numbers as input from the user and produces a cumulative list where each element in the list at any position n is sum of all elements at positions upto n-1.
Solution:
def create_cumulative_list(numbers):
cumulative_list = []
total = 0
for num in numbers:
total += num
cumulative_list.append(total)
return cumulative_list
try:
input_str = input("Enter a list of numbers separated by spaces: ")
input_numbers = [int(x) for x in input_str.split()]
cumulative_result = create_cumulative_list(input_numbers)
print("Cumulative list:", cumulative_result)
except ValueError:
print("Invalid input. Please enter valid numbers separated by spaces.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Question 12. Write a Python Program to find the sum of any three prime number.
Solution:
def is_prime(n):
return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))
primes = [x for x in range(2, 100) if is_prime(x)]
sum_of_primes = sum(primes[:3])
print(f"The sum of three prime numbers is: {sum_of_primes}")
Question 13: Write a Python function that takes two lists and returns True if they have at least one common Item.
Solution:
def has_common_item(list1, list2):
# Convert the lists to sets and find their intersection
common_items = set(list1) & set(list2)
# If the intersection is not empty, there is at least one common item
return bool(common_items)
# Example usage:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
if has_common_item(list1, list2):
print("The lists have at least one common item.")
else:
print("The lists do not have any common items.")
Question 14. Write a NumPy program to find the most frequent value in an array.
Solution:
import numpy as np
# Create a NumPy array
array = np.array([1, 2, 3, 2, 1, 5, 6, 3, 2, 1])
# Find the most frequent value
most_frequent_value = np.bincount(array).argmax()
# Print the most frequent value
print(most_frequent_value)
Question 15. Take two NumPy arrays having two dimensions. Concatenate the arrays on axis 1.
Solution:
import numpy as np
# Create two sample NumPy arrays with two dimensions (2x3)
array1 = np.array([[1, 2, 3],
[4, 5, 6]])
array2 = np.array([[7, 8, 9],
[10, 11, 12]])
# Concatenate the arrays along axis 1 (columns)
concatenated_array = np.concatenate((array1, array2), axis=1)
print("Concatenated array along axis 1:")
print(concatenated_array)
Question 16. Write a Python program to combine two dictionary adding values for common keys.
d1 = {‘a’: 100, ‘b’: 200, ‘c’:300}
d2 = {‘a’: 300, ‘b’: 200, ‘d’:400}
Sample output: Counter({‘a’: 400, ‘b’: 400, ‘d’: 400, ‘c’: 300})
Solution:
from collections import Counter
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
# Combine dictionaries by adding values for common keys
combined_dict = Counter(d1)
for key, value in d2.items():
combined_dict[key] += value
print(combined_dict)
Question 17. Write a program that takes sentence as input from the user and computes the frequency of each letter. Use a variable of dictionary type to maintain and show the frequency of each letter.
Solution:
def calculate_letter_frequency(sentence):
letter_frequency = {}
for char in sentence:
if char.isalpha():
letter_frequency[char.lower()] = letter_frequency.get(char.lower(), 0) + 1
return letter_frequency
try:
user_input = input("Enter a sentence: ")
letter_count = calculate_letter_frequency(user_input)
if letter_count:
print("Letter frequency in the sentence:")
for letter, count in letter_count.items():
print(f"{letter}: {count}")
else:
print("No letters found in the sentence.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Question 18. Apply recursive call to do the following:
a) Product of two numbers using repetitive addition
b) Print Fibonacci series upto term n
Solution:
# a) Product of two numbers using repetitive addition
def product_recursive_addition(a, b):
if b == 0:
return 0
if b < 0:
return -product_recursive_addition(a, -b)
return a + product_recursive_addition(a, b - 1)
# b) Print Fibonacci series up to term n
def fibonacci_recursive(n, a=0, b=1):
if n <= 0:
return
print(a, end=" ")
fibonacci_recursive(n - 1, b, a + b)
# Example usage for product_recursive_addition
num1 = 6
num2 = 7
product = product_recursive_addition(num1, num2)
print(f"Product of {num1} and {num2} is: {product}")
# Example usage for fibonacci_recursive
n_terms = 10
print(f"\nFibonacci series up to {n_terms} terms:")
fibonacci_recursive(n_terms)
Question 19. Write a program to input two numbers as input and compute the greatest common divisor.
Solution:
import math
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
gcd = math.gcd(num1, num2)
print(f"The Greatest Common Divisor (GCD) of {num1} and {num2} is: {gcd}")
except ValueError:
print("Invalid input. Please enter valid integers.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Question 20. Write a program to replace ‘a’ with ‘b’, ‘b’ with ‘c’,….,’z’ with ‘a’ and similarly for ‘A’ with ‘B’,’B’ with ‘C’, …., ‘Z’ with ‘A’ in a file. The other characters should remain unchanged.
Solution:
def replace_chars(input_string):
result = ""
for char in input_string:
if 'a' <= char <= 'z':
new_char = chr(((ord(char) - ord('a') + 1) % 26) + ord('a'))
elif 'A' <= char <= 'Z':
new_char = chr(((ord(char) - ord('A') + 1) % 26) + ord('A'))
else:
new_char = char
result += new_char
return result
try:
file_name = input("Enter the name of the file: ")
with open(file_name, 'r') as file:
file_content = file.read()
modified_content = replace_chars(file_content)
with open(file_name, 'w') as file:
file.write(modified_content)
print(f"File '{file_name}' has been modified.")
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Also Read: How To Make WordPress Plugin Using AI