Updated on 17-02-2024
Loops
Easy:
1. Write a Python for loop that prints numbers from 1 to 5.
2. Create a for loop that iterates over the characters in the string "PYTHON" and prints each
character.
3. Write a nested for loop to generate the following pattern:
**
***
****
1. Use a for loop to iterate through numbers from 1 to 10, but stop the loop when the number
is 7.
Medium:
1. Implement a while loop to find and print the factorial of a given number
2. Write a Python program to reverse a given string using a for loop.
3. Implement a Python program to print a number triangle as follows:
1
22
333
4444
1. Write a Python program to generate the first few rows of Pascal's Triangle. For example:
1
11
121
1331
1. Create a Python program to print a diamond pattern using asterisks. For instance:
*
***
*****
*******
*****
***
*
(LOOP)Difficult:
1. Find the area under curve for graph y = x^2 in interval 0 to 10. The error should be
less than 1 %. (Hint: use technique of approximation to convert the area into
rectangles of approximate value )
2. Find the value of e^x upto 50 terms using expansion series
3. Write a program to take user input of 10 integer numbers (numbers could be repeating) for
creating a list of integers and then use Python inbuilt Dictionary data type to convert that above list
of numbers into dictionary where the keys of dictionary will be unique numbers of the list and the
value will be the frequency of each numbers in the list respectively.
4. Use iterative loops to find the value of a function whose derivative is given:
dy/dy = x and at x = 0 , y = 0
Find value of y at x = 10 ( you can run the loop as many times as you want )
Please comment how the accuracy of value of y is dependent on number of iterations of loop
5. Take this list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and arrange it in reverse order . (You are free to use
Python inbuilt functions such as append() )
String
Easy:
1. Given two strings "hello" and "world", write a Python program using a for loop to
concatenate them and print the result.
2. Write a Python program using a for loop to count the number of occurrences of the letter 'a'
in the string "banana".
3. Create a function that takes a string as input and converts it to uppercase using a for loop.
4. Using a while loop, find and print the length of the string "programming".
Medium:
1. Implement a Python program to check if the string "level" is a palindrome (reads the same
backward as forward) using a loop.
2. Write a function that takes a string as input and uses a for loop to count the number of
vowels (a, e, i, o, u) in the string.
3. Given the string "abcde", write a Python program using a for loop to swap adjacent
characters and print the modified string.
4. Write a Python program to find and print the unique characters in the string "hello" using a
loop.
List
Easy
1. Create a Python list containing the first five even numbers (2, 4, 6, 8, 10).
2. Given the list [1, 2, 3, 4, 5], write Python code to access and print the third element.
3. Combine the lists [1, 2, 3] and [4, 5, 6] using a + operator and print the result.
4. Determine and print the length of the list [7, 8, 9, 10] using a while loop.
5. Create a Python program that takes a number as input and generates a list with that number
repeated five times.
6. Given the list [10, 15, 20, 25, 30], use a for loop to create a new list containing only the
numbers divisible by 3.
Medium:
1. Implement a Python program to reverse the elements in the list [1, 2, 3, 4, 5] without using
the reverse() method.
2. Given two lists [10, 20, 30] and [40, 50, 60], merge them alternately to create a new list [10,
40, 20, 50, 30, 60].
3. Write a Python program to check if the list [1, 2, 3, 2, 1] is a palindrome (reads the same
backward as forward).
4. Create a function that takes a list as input and uses a loop to determine if all elements in the
list are unique.
1.
Tuples
Easy: some of question for which you must guess the output
1. tuple_1 = (1, 2, 3, 4, 5)
print(tuple_1[2]) ?
2. tuple_2 = ('apple', 'orange', 'banana')
print(len(tuple_2))?
3. tuple_3 = (10, 20, 30)
tuple_4 = (40, 50, 60)
result_tuple = tuple_3 + tuple_4
print(result_tuple)?
4. tuple_5 = ('a', 'b', 'c', 'd')
print(tuple_5[1:3])?
5. tuple_7 = ('cat', 'dog', 'fish')
if 'cat' in tuple_7:
print("Found!")
else:
print("Not Found!")
Medium:
1. tuple_d = (3, 6, 9, 12, 15)
new_list = []
for x in tuple_d:
new_list.append(x // 3)
print(new_list)?
2. tuple_e = ('apple', 'orange', 'banana', 'kiwi')
new_tuple = tuple(sorted(tuple_e))
print(new_tuple)?
3. tuple_g = ('a', 'b', 'c', 'd', 'e')
reversed_tuple = tuple()
for item in reversed(tuple_g):
reversed_tuple += (item,)
print(reversed_tuple)?
4. tuple_h = (2, 4, 6, 8, 10)
odd_count = 0
for num in tuple_h:
if num % 2 != 0:
odd_count += 1
print(odd_count)?
5. tuple_j = (1, 2, 3, 4, 5)
tuple_k = tuple_j[:3] + (10, 20, 30) + tuple_j[3:]
print(tuple_k)?
Matrices
Easy: guess the output
1. matrix_a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix_a:
print(row)?
2. matrix_b = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
element = matrix_b[1][2]
print(element)
3. matrix_d = [
[3, 0, 0],
[0, 5, 0],
[0, 0, 8]
]
sum_diagonal = sum(matrix_d[i][i] for i in range(len(matrix_d)))
print(sum_diagonal)?
Medium:
1. matrix_e = [
[5, 6, 7],
[8, 9, 10],
[11, 12, 13]
]
matrix_f = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
result_matrix_sub = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(len(matrix_e)):
for j in range(len(matrix_e[0])):
result_matrix_sub[i][j] = matrix_e[i][j] - matrix_f[i][j]
for row in result_matrix_sub:
print(row)?
2. matrix_g = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
transposed_matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(len(matrix_g)):
for j in range(len(matrix_g[0])):
transposed_matrix[j][i] = matrix_g[i][j]
for row in transposed_matrix:
print(row)?
Difficult Matrix:
1. Take user input matrix A (3X3) and B (3x3) and multiply them to get the Matrix C .
(Please experiment with changing the loop order and see if it makes any difference, if yes/no please
comment why?
Hint: for taking user input Matrix, use lists of python and nested lists are used for Matrix
representation.
2. For a given matrix, print its transpose matrix.
3. For a given matrix, write a program to calculate the determinant of the matrix.
4. Write a Program to Convert a matrix in upper diagonal matrix after row operation
If- else condition
Easy:
1. Write a Python program that takes an integer input from the user and prints whether it is
positive or negative.
2. Create a program that prompts the user for an integer and determines whether it is even or
odd.
3. Write a program that takes three numbers as input and prints the largest among them.
4. Create a program that takes a single character as input and prints whether it is a vowel or a
consonant.
Medium: guess the output
1. x = 15
if x > 10:
print("Greater than 10")
else:
print("Less than or equal to 10")
2. score = 78
if score >= 90:
print("A")
elif 80 <= score < 90:
print("B")
elif 70 <= score < 80:
print("C")
else:
print("Fail")
3 . price = 120
discount = 20
final_price = price - (price * discount / 100)
if final_price > 100:
print("High Price")
else:
print("Low Price")
4 temperature = 28
if temperature >= 30:
print("Hot")
elif 20 <= temperature < 30:
print("Moderate")
else:
print("Cold")
Conditonals (Medium/Hard):
1. Given two 100 -digit number, write a program to find the bigger number.
(Hint: Iterate through digits to compare)
2.Find the largest and smallest number in the list [7, 5, 2, 9, 0,1 2, 7, 3, 8]
Recursion
1. def countdown(n):
if n <= 0:
return
print(n)
countdown(n - 1)
countdown(5)?
2. def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
result = factorial(4)
print(result)?
3. def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
result = fibonacci(5)
print(result)?
4. def palindrome_check(word):
if len(word) <= 1:
return True
if word[0] != word[-1]:
return False
return palindrome_check(word[1:-1])
result = palindrome_check("level")
print(result)
5. def sum_of_digits(n):
if n < 10:
return n
return n % 10 + sum_of_digits(n // 10)
result = sum_of_digits(123)
print(result)
6. def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
result = gcd(24, 36)
print(result)?
7. def f(n):
if n <= 0:
return 1
else:
return n * g(n - 1)
def g(n):
if n <= 0:
return 1
else:
return n + f(n - 1)
result = f(3)
print(result)
8. def f(n):
if n == 0:
return 1
else:
return n * g(n - 1)
def g(n):
if n == 0:
return 1
else:
return n + f(n - 1)
def h(n):
if n == 0:
return 1
else:
return n - h(n - 1)
result = h(3)
print(result)
9. def f(n):
if n == 0:
return 1
else:
return n * g(n - 1) - h(n - 1)
def g(n):
if n == 0:
return 1
else:
return n + f(n - 1) - h(n - 1)
def h(n):
if n == 0:
return 1
else:
return n - h(n - 1) + i(n - 1)
def i(n):
if n == 0:
return 1
else:
return n + i(n - 1) - h(n - 1)
result = f(4)
print(result)?
Try to figure out the number of function calls to f(),g(),h(),i(0 as well as the result. Which function
was called the maximum number of times?
Dictionary
1.
student = {"name": "John", "age": 20, "grade": "A"}
print("Name:", student["name"])
print("Age:", student["age"])
print("Grade:", student["grade"])
2.
car = {"brand": "Toyota", "model": "Camry", "year": 2020}
car["year"] = 2022
car["color"] = "Blue"
print("Updated Dictionary:", car)
3.
employee = {"name": "Alice", "position": "Manager", "salary": 50000}
for key, value in employee.items():
print(key + ":", value)
4.
# Creating a dictionary
fruit_stock = {"apple": 10, "orange": 5, "banana": 8}
# Checking if a key is in the dictionary
print("Is 'apple' in stock?", "Yes" if 'apple' in fruit_stock else "No")
# Getting the keys and values as lists
keys_list = list(fruit_stock.keys())
values_list = list(fruit_stock.values())
print("Keys:", keys_list)
print("Values:", values_list)
5.
# Creating a dictionary
book = {"title": "Python Programming", "author": "John Smith", "pages": 300}
# Deleting a key-value pair
del book["pages"]
print("Updated Dictionary:", book)
6.
from collections import defaultdict
fruit_inventory = defaultdict(int)
fruit_inventory["apple"] += 5
fruit_inventory["banana"] += 3
print("Fruit Inventory:", dict(fruit_inventory))
Set
1.
# Creating a set
fruits = {"apple", "orange", "banana", "apple"}
# Displaying the set
print("Fruits Set:", fruits)
# Adding an element to the set
fruits.add("grape")
# Removing an element from the set
fruits.remove("orange")
# Checking membership in the set
print("Is 'banana' in the set?", "Yes" if 'banana' in fruits else "No")
2.
# Creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union of sets
union_set = set1.union(set2)
# Intersection of sets
intersection_set = set1.intersection(set2)
# Difference of sets
difference_set = set1.difference(set2)
print("Union Set:", union_set)
print("Intersection Set:", intersection_set)
print("Difference Set:", difference_set)
3.
# Creating sets
set_a = {1, 2, 3, 4, 5}
set_b = {2, 4}
# Checking if set_b is a subset of set_a
is_subset = set_b.issubset(set_a)
print("Is set_b a subset of set_a?", "Yes" if is_subset else "No")
4.
# Creating sets
set_a = {1, 2, 3, 4, 5}
set_b = {2, 4}
# Checking if set_b is a subset of set_a
is_subset = True
for elem in set_b:
if elem not in set_a:
is_subset = False
break
print("Is set_b a subset of set_a?", "Yes" if is_subset else "No")
6.
# Creating a set
colors = {"red", "blue", "green", "yellow"}
# Removing and displaying a random element using pop
if colors:
removed_color = next(iter(colors))
colors.remove(removed_color)
print("Removed Color:", removed_color)
else:
print("Set is empty")
# Clearing the set
colors = set()
print("Cleared Set:", colors)