0% found this document useful (0 votes)
5 views17 pages

Sheet Solutions

The document contains a programming exam with 30 tasks focused on Python programming. Each task includes a specific requirement, such as checking if a number is even or odd, finding the largest number in a list, or creating graphical elements using Tkinter. The tasks cover a range of topics including string manipulation, data structures, and random number generation.
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)
5 views17 pages

Sheet Solutions

The document contains a programming exam with 30 tasks focused on Python programming. Each task includes a specific requirement, such as checking if a number is even or odd, finding the largest number in a list, or creating graphical elements using Tkinter. The tasks cover a range of topics including string manipulation, data structures, and random number generation.
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/ 17

Programming Exam

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

# Get input from the user


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

# Check if the number is even or odd


if number % 2 == 0:
print("Even")
else:
print("Odd")

2. Write a Python program that takes two integers as input and prints the larger of
the two numbers

# Get input from the user


num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))

# Compare the two numbers


if num1 > num2:
print(num1)
else:
print(num2)

3. Write a Python program that takes a string as input and checks if it is a


palindrome. If it is, the program should print "Palindrome", and if it is not, the
program should print "Not a Palindrome".

# Get input from the user


input_string = input("Enter a string: ")

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.

# Get input from the user


numbers =
input("Enter a list of integers separated by spaces: ").split()
numbers = [int(num) for num in numbers]

# Calculate the sum of positive integers


positive_sum = 0
for num in numbers:
if num > 0:
positive_sum += num

print("Sum of positive integers:", positive_sum)

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.

# Get input from the user


input_string = input("Enter a string: ")

# Count the number of vowels


vowels = "aeiouAEIOU"
vowel_count = 0
for char in input_string:
if char in vowels:
vowel_count += 1

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.

# Get input from the user


numbers = input("Enter a list of numbers separated by spaces: ")
numbers = [int(num) for num in numbers]

# Create a dictionary of squares


squares_dict = {}
for num in numbers:
squares_dict[num] = num ** 2

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.

# Example input dictionary


input_dict = {'a': 1, 'b': 'two', 'c': 3, 'd': 'four'}

# Create a new dictionary with only integer values


int_values_dict = {}
for k, v in input_dict.items():
if isinstance(v, int):
int_values_dict[k] = v

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}

# Find common key-value pairs


common_dict = {}
for k in dict1:
if k in dict2 and dict1[k] == dict2[k]:
common_dict[k] = dict1[k]

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.

# Example list of tuples


tuples_list = [("Alice", "[email protected]"),
("Bob", "[email protected]"), ("Charlie", "[email protected]")]

# Create a dictionary from the list of tuples


email_dict = {}
for name, email in tuples_list:
email_dict[email] = name

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}

# Find the key with the highest value

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

print("Key with the highest value:", max_key)

11. Write a Python program that draws a rectangle on a canvas with a specified
width, height, and color.

import tkinter as tk

def draw_rectangle(width, height, color):


root = tk.Tk()
canvas = tk.Canvas(root, width=width+20, height=height+20)
canvas.pack()
canvas.create_rectangle(10, 10, 10 + width, 10 + height,
fill=color)
root.mainloop()

# 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

def draw_circle(radius, center_x, center_y, color):


root = tk.Tk()
canvas = tk.Canvas(root, width=center_x * 2 + 20, height=cen
canvas.pack()
canvas.create_oval(center_x - radius, center_y - radius,
center_x + radius, center_y + radius,

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

def draw_line(start_x, start_y, end_x, end_y, thickness, color)


root = tk.Tk()
canvas = tk.Canvas(root, width=max(start_x, end_x) + 20, hei
canvas.pack()
canvas.create_line(start_x, start_y, end_x, end_y, width=thi
root.mainloop()

# 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

def display_image(image_path, canvas_width, canvas_height, posit


root = tk.Tk()
canvas = tk.Canvas(root, width=canvas_width, height=canvas_h
canvas.pack()

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

def display_text(canvas_width, canvas_height, bg_color, text, fo


root = tk.Tk()
canvas = tk.Canvas(root, width=canvas_width, height=canvas_h
canvas.pack()

canvas.create_text(position_x, position_y, text=text, font=(


root.mainloop()

# 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

# Generate a random number


random_number = random.randint(1, 100)

# Guessing game loop


while True:
guess = int(input("Guess the number (between 1 and 100): "))

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

# Generate a list of 10 random integers


random_integers = [random.randint(1, 100) for _ in range(10)]

# Find the largest and smallest numbers


largest = max(random_integers)
smallest = min(random_integers)

# Print the results


print("List of random integers:", random_integers)
print("Largest number:", largest)
print("Smallest number:", smallest)

18. Write a Python program that generates a random password of length 10


consisting of random uppercase and lowercase letters, digits, and special
characters

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

# Generate and print a random password


print("Random password:", generate_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

# Example list of integers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Shuffle the list


random.shuffle(numbers)

# Print the shuffled list


print("Shuffled list:", numbers)

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)

# Print the random walk


print("Random walk (first 10 steps):", walk[:10])

21. Write a Python program that takes a string as input and reverses the order of
the characters in the string.

# Get input from the user


input_string = input("Enter a string: ")

# Reverse the string


reversed_string = input_string[::-1]

# Print the reversed string


print("Reversed string:", reversed_string)

22. Write a Python program that takes a string as input and removes all the vowels
in the string

# Get input from the user


input_string = input("Enter a string: ")

# Remove vowels from the string


vowels = "aeiouAEIOU"
no_vowels_string = ''.join(char for char in input_string if char

# Print the result


print("String without vowels:", no_vowels_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

# Get input from the user


input_string = input("Enter a string: ")

# Check if the string is a pangram


alphabet = set(string.ascii_lowercase)
is_pangram = alphabet <= set(input_string.lower())

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

# Get input from the user


input_string = input("Enter a string: ")

# Count the occurrences of each character


char_count = {}
for char in input_string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1

# Print the result


print(char_count)

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.

# Get input from the user


input_strings = input("Enter a list of strings separated by spac

# Find palindromes in the list


palindromes = []
for s in input_strings:
if s == s[::-1]:
palindromes.append(s)

# Print the result


print("Palindromes in the list:", palindromes)

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

def are_anagrams(str1, str2):


return sorted(str1) == sorted(str2)

# 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 deposit(self, amount):


self.balance += amount

def withdraw(self, amount):


if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient funds")

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 accelerate(self, increase):


self.speed += increase

def brake(self, decrease):


self.speed -= decrease
if self.speed < 0:
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

You might also like