QUESTION 1
A simple Python program that prompts the user for their personal information, calculates the
year they will turn 100 years old, and checks whether a given number is even or odd.
# Function to calculate the year the user will turn 100
def calculate_hundred_year(age):
current_year = 2024 # Specify the current year explicitly
return current_year + (100 - age)
# Function to check if a number is even or odd
def check_even_odd(number):
if number % 2 == 0:
return "That's an even number!"
else:
return "That's an odd number!"
# Main program
def main():
# Collecting user information
name = input("Enter your name: ")
surname = input("Enter your surname: ")
registration_number = input("Enter your registration number: ")
programme = input("Enter your programme: ")
level = input("Enter your level: ")
age = int(input("Enter your age: "))
# Calculating the year the user will turn 100
year_turn_100 = calculate_hundred_year(age)
# Printing the message
print(f"\nHello, {name} {surname}! You will turn 100 years old in the year
{year_turn_100}.")
# Asking for a number and checking if it's even or odd
number = int(input("Enter a number: "))
message = check_even_odd(number)
print(message)
# Running the main program
if __name__ == "__main__":
main()
OUTPUT
QUESTION 2
A Python program that calculates the net income after deductions based on the specified tax
rates:
def calculate_net_income(gross_income):
# Define tax brackets
if gross_income <= 15000:
tax = 0
elif gross_income <= 30000:
tax = (gross_income - 15000) * 0.05
else:
tax = (15000 * 0) + ((30000 - 15000) * 0.05) + ((gross_income - 30000)
* 0.10)
# Calculate net income
net_income = gross_income - tax
return net_income, tax
def main():
# Ask the user for gross income
gross_income = float(input("Enter your gross income (in ZWG): "))
# Calculate net income and tax
net_income, tax = calculate_net_income(gross_income)
# Display results
print(f"\nGross Income: ZWG{gross_income:.2f}")
print(f"Tax Deducted: ZWG{tax:.2f}")
print(f"Net Income: ZWG{net_income:.2f}")
# Run the program
if __name__ == "__main__":
main()
OUTPUT
QUESTION 3
Python program that implements a BankBalance class according to your specifications. The
program allows a user to enter their bank balance, withdraw an amount, apply interest, and
handle overdraft options:
class BankBalance:
def __init__(self, initial_balance):
[Link] = initial_balance
def apply_interest(self):
if [Link] >= 1: # Check if the balance is at least ZWG 1
[Link] += [Link] * 0.05 / 12 # Monthly interest
def withdraw(self, amount):
if amount > [Link]:
print("Insufficient balance!")
choice = input("Do you want to overdraft? (yes/no):
").strip().lower()
if choice == 'yes':
[Link] -= amount
[Link] -= 8 # Apply penalty
print(f"Overdraft applied. Penalty of ZWG 8 charged.")
else:
print("Withdrawal canceled. Balance remains unchanged.")
else:
[Link] -= amount
def get_balance(self):
return [Link]
def main():
# Get initial balance from the user
initial_balance = float(input("Enter your initial bank balance (in ZWG):
"))
bank_account = BankBalance(initial_balance)
# Apply monthly interest
bank_account.apply_interest()
# Ask user for withdrawal amount
withdrawal_amount = float(input("Enter the withdrawal amount (in ZWG): "))
bank_account.withdraw(withdrawal_amount)
# Display the final balance
print(f"\nFinal balance: ZWG{bank_account.get_balance():.2f}")
# Run the program
if __name__ == "__main__":
main()
OUTPUT
If the customer withdraws more than the bank balance:
QUESTION 4
A Python program that allows a user to enter 10 temperatures, calculates the average
temperature, and then displays which temperatures are above and below the average:
def main():
# Initialize an empty list to store temperatures
temperatures = []
# Read 10 temperatures from the user
print("Enter 10 temperatures (in decimals):")
for i in range(10):
temp = float(input(f"Temperature {i + 1}: "))
[Link](temp)
# Calculate the average temperature
average_temperature = sum(temperatures) / len(temperatures)
# Display the average temperature
print(f"\nAverage Temperature: {average_temperature:.2f}")
# Find and display temperatures above and below the average
above_average = [temp for temp in temperatures if temp >
average_temperature]
below_average = [temp for temp in temperatures if temp <
average_temperature]
print("\nTemperatures above the average:")
for temp in above_average:
print(f"{temp:.2f}")
print("\nTemperatures below the average:")
for temp in below_average:
print(f"{temp:.2f}")
# Run the program
if __name__ == "__main__":
main()
OUTPUT
QUESTION 5
A Python program that calculates how much money Johnny takes home after spending some of
his pocket money at the school's tuck shop, including VAT
def main():
# Initial pocket money
initial_amount = 100.0 # Johnny's starting pocket money
# Prices of items
prices = {
"crisps": 8.0,
"hotdog": 12.0,
"juice": 5.0
}
# Calculate total spending
total_spent = sum([Link]())
# VAT rate (assuming 15% for this example)
vat_rate = 0.15
total_with_vat = total_spent * (1 + vat_rate)
# Calculate remaining money
money_left = initial_amount - total_with_vat
# Display results
print(f"Total money spent (excluding VAT): ${total_spent:.2f}")
print(f"Total money spent (including VAT): ${total_with_vat:.2f}")
print(f"Money left after spending: ${money_left:.2f}")
if __name__ == "__main__":
main()
OUTPUT
QUESTION 6
A Python program that allows the user to enter their height in meters, then converts that height to
feet using a class method:
class HeightConverter:
def __init__(self, height_meters):
self.height_meters = height_meters
def convert_to_feet(self):
# Convert height to feet
height_feet = self.height_meters * 3.281
return height_feet
def main():
# Prompt the user to enter their height in meters
height_meters = float(input("Enter your height in meters: "))
# Create an instance of HeightConverter
height_converter = HeightConverter(height_meters)
# Convert height to feet and display the result
height_feet = height_converter.convert_to_feet()
print(f"Your height in feet: {height_feet:.2f} ft")
if __name__ == "__main__":
main()
OUTPUT
QUESTION 7
A Python program that defines a Car class with the specified features, including a constructor,
getter and setter methods, and a method to classify the car based on its top speed:
class Car:
def __init__(self, make, model, top_speed):
[Link] = make
[Link] = model
self.top_speed = top_speed
# Getter methods
def get_make(self):
return [Link]
def get_model(self):
return [Link]
def get_top_speed(self):
return self.top_speed
# Setter methods
def set_make(self, make):
[Link] = make
def set_model(self, model):
[Link] = model
def set_top_speed(self, top_speed):
self.top_speed = top_speed
# Method to classify the car based on top speed
def classify(self):
if self.top_speed > 250:
return "Super Car"
elif self.top_speed < 100:
return "Jalopy"
else:
return "Family Sedan"
def main():
# Create a Car object
make = input("Enter the car's make: ")
model = input("Enter the car's model: ")
top_speed = float(input("Enter the car's top speed (in km/h): "))
car = Car(make, model, top_speed)
# Display car details and classification
print(f"\nCar Make: {car.get_make()}")
print(f"Car Model: {car.get_model()}")
print(f"Top Speed: {car.get_top_speed()} km/h")
print(f"Classification: {[Link]()}")
if __name__ == "__main__":
main()
OUTPUT
QUESTION 8
A Python program that analyzes rainfall in Zimbabwe based on the user's input for the month
and total rainfall for that month. It determines the month name, whether it falls in winter or
summer, and compares the total rainfall to the average rainfall for that season.
def get_month_name(month):
month_names = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
return month_names.get(month, "Invalid month")
def get_season(month):
if month in [6, 7, 8]: # Winter months
return "Winter", 10
elif month in [11, 12, 1, 2, 3, 4, 5, 6]: # Summer months
return "Summer", 80
else:
return None, None # Invalid month
def main():
# Input month and total rainfall
month = int(input("Enter the month as an integer (1-12): "))
total_rainfall = float(input("Enter the total rainfall for the month (in
mm): "))
# Get month name
month_name = get_month_name(month)
# Get season and average rainfall
season, average_rainfall = get_season(month)
if season is None:
print("Invalid month entered.")
return
# Output results
print(f"\nMonth: {month_name}")
print(f"Season: {season}")
if total_rainfall > average_rainfall:
comparison = "greater than"
elif total_rainfall < average_rainfall:
comparison = "less than"
else:
comparison = "equal to"
print(f"The total rainfall for the month is {comparison} the average
rainfall of {average_rainfall} mm.")
# Run the program
if __name__ == "__main__":
main()
OUTPUT
QUESTION 9
A simple Python program that implement the functional described. This program will allow the
user to enter integer values until they input 999, after which it will display the sum of the values
entered, excluding 999.
class NumberAnalyzer:
def __init__(self):
[Link] = []
def enter_numbers(self):
while True:
try:
num = int(input("Enter an integer value (or 999 to finish):
"))
if num == 999:
break
if self.check_number(num):
[Link](num)
else:
print("Please enter a valid integer.")
except ValueError:
print("Invalid input. Please enter an integer.")
def check_number(self, number):
# Check if the number is an integer
return isinstance(number, int)
def display_sum(self):
total_sum = sum([Link])
print(f"The sum of the values entered (excluding 999) is:
{total_sum}")
def main():
analyzer = NumberAnalyzer()
analyzer.enter_numbers() # Invoke method to enter numbers
analyzer.display_sum() # Invoke method to display the sum
if __name__ == "__main__":
main()
OUTPUT
QUESTION 10
A Python program that defines the methods AddInt(), AddDouble(), and TotalCalculation(). Each
method handles its respective task, and the results are combined to show the total as a decimal
number. A while loop is used to control the flow of the program.
def add_int():
total = 0
count = 0
while count < 5:
try:
num = int(input(f"Enter integer {count + 1}: "))
total += num
count += 1
except ValueError:
print("Invalid input. Please enter an integer.")
return total
def add_double():
total = 0.0
count = 0
while count < 3:
try:
num = float(input(f"Enter decimal number {count + 1}: "))
total += num
count += 1
except ValueError:
print("Invalid input. Please enter a decimal number.")
return total
def total_calculation():
int_sum = add_int() # Add 5 integers
double_sum = add_double() # Add 3 decimals
total = int_sum + double_sum # Calculate total
print(f"The total of integers and decimals is: {total:.2f}")
def main():
total_calculation() # Invoke the total calculation
if __name__ == "__main__":
main()
OUTPUT
QUESTION 11
A python program in which a user can continue entering integers.
def main():
print("Enter integers continuously. Type 'q' to quit.")
while True:
user_input = input("Enter an integer (or 'q' to quit): ")
if user_input.lower() == 'q':
print("Exiting the program. Goodbye!")
break
try:
number = int(user_input) # Try to convert the input to an integer
print(f"You entered: {number}") # Display the valid integer
except ValueError:
print("Invalid input. Please enter a valid integer or 'q' to
quit.")
if __name__ == "__main__":
main()
OUTPUT
QUESTION 12
A Python program that creates a list containing both integers and floats. It demonstrates how
to use a for loop to print the contents of the list and how to print the elements from index
position 2 to 5.
# Create a list of numbers including integers and floats
numbers = [10, 15.5, 23, 42.8, 5, 100.0]
# a) Using a for loop, print the content of this list
print("Content of the list:")
for number in numbers:
print(number)
# b) Print the elements from index position 2 to 5
print("\nElements from index position 2 to 5:")
for i in range(2, 6):
print(numbers[i])
OUTPUT
QUESTION 13
A Python program using the turtle graphics library to draw a red circle, a yellow circle
underneath it, and a green circle underneath that
import turtle
# Function to draw a circle of a given color and position
def draw_circle(color, x, y):
[Link]() # Don't draw when moving to the position
[Link](x, y) # Move to the specified position
[Link]() # Start drawing
[Link](color) # Set the circle color
turtle.begin_fill() # Begin filling the circle
[Link](50) # Draw a circle with radius 50
turtle.end_fill() # End filling
# Set up the turtle environment
[Link](1) # Set the drawing speed
[Link]("Colored Circles") # Set the window title
# Draw the circles
draw_circle("red", 0, 0) # Red circle at (0, 0)
draw_circle("yellow", 0, -100) # Yellow circle underneath
draw_circle("green", 0, -200) # Green circle underneath
# Finish drawing
[Link]() # Hide the turtle cursor
[Link]() # Complete the drawing
OUTPUT
QUESTION 14
A simple RPG character class in Python that meets your requirements. This class includes a
name, a money pouch, and an inventory. It also has methods for adding and removing items
from the inventory, as well as a __str__ method for easy printing.
class Pouch:
def __init__(self, initial_amount=0):
[Link] = initial_amount
def add_money(self, amount):
[Link] += amount
def remove_money(self, amount):
if amount <= [Link]:
[Link] -= amount
else:
print("Not enough money in the pouch!")
def __str__(self):
return f"{[Link]} gold pieces"
class Character:
def __init__(self, name, initial_money=0):
[Link] = name
[Link] = Pouch(initial_money)
[Link] = {}
def add_item(self, item_name, quantity=1):
if item_name in [Link]:
[Link][item_name] += quantity
else:
[Link][item_name] = quantity
def remove_item(self, item_name, quantity=1):
if item_name in [Link]:
if [Link][item_name] >= quantity:
[Link][item_name] -= quantity
if [Link][item_name] == 0:
del [Link][item_name]
else:
print(f"Not enough {item_name} in the inventory!")
else:
print(f"{item_name} not found in inventory!")
def __str__(self):
inventory_items = ', '.join(f"{item}: {quantity}" for item, quantity
in [Link]())
inventory_display = f"Knapsack contains: {inventory_items}" if
inventory_items else "Knapsack is empty."
return (f"------------------------\n"
f"{[Link]}\n"
f"------------------------\n"
f"Money: {[Link]}\n"
f"{inventory_display}\n"
f"------------------------")
# Example usage
if __name__ == "__main__":
playerA = Character("Duncan Disorderly", 235)
playerA.add_item("Arrow", 12)
playerA.add_item("Rubber Sword", 1)
playerA.add_item("Felt-tipped pen", 2)
playerA.add_item("Imitation fur coat", 23)
print(playerA)
# Example of removing an item
playerA.remove_item("Arrow", 5)
print(playerA)
OUTPUT
SIMPLE PROJECT
A Python program that implements a number-guessing game with the features : random
number generation, user input handling, feedback on guesses, a timer, a limit on the number of
guesses, and a scoring system based on the number of attempts and time taken.
import random
import time
def play_game():
number_to_guess = [Link](1, 100)
attempts = 0
max_attempts = 10
time_limit = 30 # seconds
print("Welcome to the Number Guessing Game!")
print("I have selected a number between 1 and 100.")
print(f"You have {max_attempts} attempts and {time_limit} seconds to guess
it.")
start_time = [Link]()
while attempts < max_attempts:
remaining_time = time_limit - ([Link]() - start_time)
if remaining_time <= 0:
print("Time's up! You didn't guess the number in time.")
break
try:
guess = int(input(f"Attempt {attempts + 1}: Enter your guess (1-
100): "))
except ValueError:
print("Please enter a valid number.")
continue
attempts += 1
if guess < 1 or guess > 100:
print("Your guess is out of bounds. Please guess a number between
1 and 100.")
elif guess < number_to_guess:
print("Too low! Try again.")
elif guess > number_to_guess:
print("Too high! Try again.")
else:
elapsed_time = [Link]() - start_time
score = max(0, (time_limit - elapsed_time) * (max_attempts -
attempts + 1))
print(
f"Congratulations! You guessed the number {number_to_guess} in
{attempts} attempts and {elapsed_time:.2f} seconds.")
print(f"Your score: {score:.2f}")
break
else:
print(f"You've used all your attempts. The number was
{number_to_guess}.")
def main():
while True:
plaay_game()
play_again = input("Do you want to play again? (y/n):
").strip().lower()
if play_again != 'y':
break
print("Thanks for playing!")
if __name__ == "__main__":
main()
OUTPUT