Sheet Solutions
Sheet Solutions
1. Write a Python program that takes an integer as input and prints "Even" if the
number is even, and "Odd" if the number is odd
2. Write a Python program that takes two integers as input and prints the larger of
the two numbers
Programming Exam 1
# Check if the string is a palindrome
if input_string == input_string[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
4. Write a Python program that takes a list of integers as input and prints the
sum of all the positive integers in the list.
5. Write a Python program that takes a string as input and counts the number of
vowels in the string. The program should then print the number of vowels found in
the string.
Programming Exam 2
print("Number of vowels:", vowel_count)
6. Write a Python program that takes a list of numbers and returns a dictionary
where the keys are the numbers in the list and the values are the squares of those
numbers.
print(squares_dict)
7. Write a Python program that takes a dictionary as input and returns a new
dictionary that contains only the key-value pairs where the value is an integer.
print(int_values_dict)
8. Write a Python program that takes two dictionaries as input and returns a new
dictionary that contains the key-value pairs that are common to both dictionaries.
Programming Exam 3
# Example dictionaries
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 2, 'c': 4, 'd': 5}
print(common_dict)
9. Write a Python program that takes a list of tuples, where each tuple contains
two strings representing a name and an email address, and returns a dictionary
where the keys are the email addresses and the values are the names associated
with those email addresses.
print(email_dict)
10. Write a Python program that takes a dictionary as input and returns the key
that has the highest value.
# Example dictionary
input_dict = {'a': 10, 'b': 20, 'c': 15}
Programming Exam 4
max_key = None
max_value = float('-inf')
for k, v in input_dict.items():
if v > max_value:
max_value = v
max_key = k
11. Write a Python program that draws a rectangle on a canvas with a specified
width, height, and color.
import tkinter as tk
# Example usage
draw_rectangle(200, 100, "blue")
12. Write a Python program that draws a circle on a canvas with a specified radius,
center coordinates, and color.
import tkinter as tk
Programming Exam 5
fill=color)
root.mainloop()
# Example usage
draw_circle(50, 100, 100, "red")
13. Write a Python program that draws a line on a canvas with a specified starting
and ending point, line thickness, and color
import tkinter as tk
# Example usage
draw_line(50, 50, 200, 200, 5, "green")
14. Write a Python program that creates a canvas with a specified width and
height and displays an image on it with a specified position and size.
import tkinter as tk
from PIL import Image, ImageTk
image = Image.open(image_path)
image = image.resize((size_width, size_height), Image.ANTIAL
tk_image = ImageTk.PhotoImage(image)
Programming Exam 6
canvas.create_image(position_x, position_y, anchor=tk.NW, im
root.mainloop()
# Example usage
display_image("path/to/your/image.jpg", 400, 400, 50, 50, 300, 3
15. Write a Python program that creates a canvas with a specified background
color and displays a text message on it with a specified font, size, color, and
position
import tkinter as tk
# Example usage
display_text(400, 400, "white", "Hello, World!", "Arial", 24, "b
16. Write a Python program that generates a random integer between 1 and 100
and asks the user to guess the number. The program should provide hints to the
user whether their guess is too high or too low until the user correctly guesses the
number.
import random
Programming Exam 7
if guess < random_number:
print("Too low!")
elif guess > random_number:
print("Too high!")
else:
print("Congratulations! You guessed the number.")
break
17. Write a Python program that generates a list of 10 random integers between 1
and 100 and then prints the largest and smallest numbers in the list
import random
import random
import string
def generate_password(length=10):
characters = string.ascii_letters + string.digits + string.p
password = ''.join(random.choice(characters) for _ in range(
Programming Exam 8
return password
19. Write a Python program that shuffles a list of integers using the
random.shuffle() method and then prints the shuffled list.
import random
20. Write a Python program that generates a random walk of length 1000
consisting of random steps in the x and y directions
import random
def random_walk(length):
x, y = 0, 0
path = [(x, y)]
for _ in range(length):
step = random.choice([(1, 0), (-1, 0), (0, 1), (0, -1)])
x += step[0]
y += step[1]
path.append((x, y))
return path
Programming Exam 9
# Generate a random walk of length 1000
walk = random_walk(1000)
21. Write a Python program that takes a string as input and reverses the order of
the characters in the string.
22. Write a Python program that takes a string as input and removes all the vowels
in the string
23. Write a Python program that takes a string as input and checks if it is a
pangram. A pangram is a sentence that contains every letter of the alphabet at
least once
Programming Exam 10
import string
if is_pangram:
print("Pangram")
else:
print("Not a Pangram")
24. Write a Python program that takes a string as input and counts the number of
occurrences of each character in the string. The program should then print a
dictionary where the keys are the characters in the string and the values are the
number of occurrences of those characters
25. Write a Python program that takes a list of strings as input and returns a new
list containing only the strings that are palindromes. A palindrome is a word or
Programming Exam 11
phrase that reads the same backwards as forwards.
26. Write a Python function that takes a list of numbers as input and returns the
sum of all the numbers in the list.
def sum_of_list(numbers):
total = 0
for num in numbers:
total += num
return total
# Example usage
numbers = [1, 2, 3, 4, 5]
print("Sum of the list:", sum_of_list(numbers))
27. Write a Python function that takes two strings as input and checks if one string
is an anagram of the other. An anagram is a word or phrase formed by rearranging
the letters of another word or phrase
# Example usage
str1 = "listen"
Programming Exam 12
str2 = "silent"
print("Are the strings anagrams?", are_anagrams(str1, str2))
28. Write a Python function that takes a list of integers as input and returns a new
list containing only the even numbers in the original list.
def filter_even_numbers(numbers):
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
return evens
# Example usage
numbers = [1, 2, 3, 4, 5, 6]
print("Even numbers in the list:", filter_even_numbers(numbers))
29. Write a Python function that takes a string as input and returns a new string
with all the vowels removed from the original string
def remove_vowels(input_string):
vowels = "aeiouAEIOU"
result_string = ""
for char in input_string:
if char not in vowels:
result_string += char
return result_string
# Example usage
input_string = "hello world"
print("String without vowels:", remove_vowels(input_string))
30. Write a Python function that takes a list of strings as input and returns a new
list containing only the strings that are palindromes. A palindrome is a word or
phrase that reads the same backwards as forwards.
Programming Exam 13
def find_palindromes(strings):
palindromes = []
for s in strings:
if s == s[::-1]:
palindromes.append(s)
return palindromes
# Example usage
strings = ["racecar", "hello", "level", "world", "radar"]
print("Palindromes in the list:", find_palindromes(strings))
31. Write a Python class called Rectangle that takes two parameters, width and
height, and has methods to calculate the area and perimeter of the rectangle.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# Example usage
rect = Rectangle(5, 10)
print("Area of the rectangle:", rect.area())
print("Perimeter of the rectangle:", rect.perimeter())
32. Write a Python class called Student that takes three parameters, name, age,
and major, and has a method to print out the student's information
class Student:
def __init__(self, name, age, major):
Programming Exam 14
self.name = name
self.age = age
self.major = major
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, Major: {self
# Example usage
student = Student("Alice", 20, "Computer Science")
student.display_info()
33. Write a Python class called BankAccount that has methods to deposit and
withdraw money from the account, as well as a method to check the balance of
the account.
class BankAccount:
def __init__(self):
self.balance = 0
def check_balance(self):
return self.balance
# Example usage
account = BankAccount()
account.deposit(100)
Programming Exam 15
account.withdraw(30)
print("Balance:", account.check_balance())
34. Write a Python class called Car that has methods to accelerate and brake the
car, as well as a method to check the current speed of the car.
class Car:
def __init__(self):
self.speed = 0
def check_speed(self):
return self.speed
# Example usage
car = Car()
car.accelerate(50)
car.brake(20)
print("Current speed:", car.check_speed())
35. Write a Python class called Animal that has methods to make the animal eat
and sleep, as well as attributes to store the animal's name and age. Create
subclasses for specific types of animals like Dog, Cat, and Bird, and give them
their own unique methods and attributes.
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
Programming Exam 16
def eat(self):
print(f"{self.name} is eating")
def sleep(self):
print(f"{self.name} is sleeping")
class Dog(Animal):
def bark(self):
print(f"{self.name} is barking")
class Cat(Animal):
def meow(self):
print(f"{self.name} is meowing")
class Bird(Animal):
def fly(self):
print(f"{self.name} is flying")
# Example usage
dog = Dog("Buddy", 3)
cat = Cat("Whiskers", 2)
bird = Bird("Tweety", 1)
dog.eat()
cat.sleep()
bird.fly()
dog.bark()
cat.meow()
Programming Exam 17