def calculate_pyramid_volume(): try : # Prompting for user inputs length = float(input("Enter the length of the pyramid (in meters): ")) width = float(input("Enter the width of the pyramid (in meters): ")) height = float(input("Enter the height of the pyramid (in meters): ")) unit = input("Enter the desired output unit (millimeters, centimeters, meters, kilometers): ") strip() lower() # Define linear conversion factors relative to 1 meter factors = { "millimeters": 1000, "centimeters": 100, "meters": 1, "kilometers": 0.001 } if unit not in factors: print(f"Error: '{unit}' is not a valid unit. Please choose from: {', ' join(factors keys())}") return # Calculate volume: (l * w * h) / 3 volume_m3 = (length * width * height) / 3 # Perform cubic conversion (factor^3) conversion_factor = factors[unit] ** 3 final_volume = volume_m3 * conversion_factor # Display final result print(f"The volume of the pyramid is: {final_volume:.6f} cubic {unit}") except ValueError: print("Error: Please enter only numbers for length, width, and height.") # Execute the program if __name__ == "__main__": calculate_pyramid_volume() The volume of the pyramid is: 170666.666667 cubic meters # 2. You’ve been hired by an Automobile company to write a program to help the tax # collector calculate vehicle taxes. Vehicle taxes are based on two pieces of information; the # price of the vehicle and the vehicle type code. # The formula of calculating the final price of an item is: # Final Price = Item Price + Tax Amount # Tax rates are in the table below # Vehicle Type Vehicle Code Tax Rate # Motorcycle M 6% # Electric E 8% # Sedan S 10% # Van V 12% # Truck T 15% # After the tax has been calculated, the program should display the following on the screen; # The final price on a vehicle of type xxx after adding the tax is $xxx. # with xxx replaced by the vehicle type and $xxx with the final price. # Your job is to write a function # float taxCalculator(char type, float price); # and then write the main function for taking the input from the user and then displaying the # final outpput def tax_calculator(vehicle_type, price): # Tax rates mapping tax_rates = { 'M': 6, # Motorcycle 'E': 8, # Electric 'S': 10, # Sedan 'V': 12, # Van 'T': 15 # Truck } # Get the rate for the type, default to 0 if not found rate = tax_rates get(vehicle_type upper(), 0) # Calculate tax amount and final price tax_amount = price * (rate / 100) final_price = price + tax_amount return final_price def main(): # User inputs type_code = input("Enter the vehicle type code (M, E, S, V, T): ") strip() upper() price_input = input("Enter the price of the vehicle: ") strip() # Remove '$' if the user entered it (as seen in your image) price_input = price_input replace('$', '') In [4]: In [5]: try : price = float(price_input) # Calculate final price using the function result = tax_calculator(type_code, price) # Display the output in the required format print(f"The final price of a vehicle of type {type_code} after adding the tax is ${result:.2f}.") except ValueError: print("Error: Please enter a valid numerical price.") if __name__ == "__main__": main() The final price of a vehicle of type M after adding the tax is $53000.00. # Q3. A firm gets a request for creating a project for which a certain number of hours are # needed. The firm has a certain number of days. During 10% of the days, the workers are being # trained and cannot work on the project. A normal working day is 8 hours long. The project is # important for the firm and every worker must work on it with overtime of 2 hours per day. # Final answer in hours must be rounded down to the nearest integer (for example, 6.98 hours # are rounded to 6 hours). # Write a program that calculates whether the firm can finish the project on time and how # many hours more are needed or left. # You have to make a function projectTimeCalculation that takes needed hours, days that # the firm has and number of workers as input and then returns the string as answer. # Input Data # The input data is read from the console and contains exactly three lines: # • On the first line are the needed hours – an integer in the range of [0 ... 200 000]. # • On the second line are the days that the firm has – an integer in the range of [0 ... 20 # 000]. # • On the third line are the number of all workers – an integer in the range of [0 ... 200]. # Output Data # Print one line on the console: # • If the time is enough: # "Yes!{the hours left} hours left.". # • If the time is NOT enough: # "Not enough time!{additional hours} hours needed." import math def projectTimeCalculation(needed_hours, days, workers): # 1. 10% of days are for training (cannot work) working_days = days * 0.9 # 2. Each worker works 10 hours/day (8 normal + 2 overtime) # Total hours = working_days * 10 hours * workers total_hours = math floor(working_days * 10 * workers) # 3. Compare and return the result string if total_hours >= needed_hours: hours_left = total_hours - needed_hours return f"Yes!{hours_left} hours left." else : hours_needed = needed_hours - total_hours return f"Not enough time! {hours_needed} hours needed." def main(): # User inputs from the console try : needed_hours = int(input("Enter the needed hours: ")) days = int(input("Enter the days that the firm has: ")) workers = int(input("Enter the number of all workers: ")) # Call function and print output result = projectTimeCalculation(needed_hours, days, workers) print(result) except ValueError: print("Please enter valid integers for all inputs.") if __name__ == "__main__": main() Yes!184 hours left. # Q4. Write a C++ program to print the appropriate activity depending on the variable # temperature and humidity value. The table below assumes that the temperature can only be # warm and cold, and the humidity can only be dry and humid. # If temperature is If humidity is Print this activity # warm dry Play tennis # warm humid swim # cold dry Play basketball # cold humid Watch tv # Write a C++ function named decideActivity that takes temperature and humidity as input In [6]: In [7]: # and returns the appropriate activity according to the condition def decide_activity(temperature, humidity): # Logic matching the provided table if temperature == "warm": if humidity == "dry": return "Play tennis" elif humidity == "humid": return "Swim" elif temperature == "cold": if humidity == "dry": return "Play basketball" elif humidity == "humid": return "Watch TV" return "Invalid input" def main(): # Prompting for user inputs matching the image scenario temp = input("Enter temperature (warm or cold): ") strip() lower() humid = input("Enter humidity (dry or humid): ") strip() lower() # Get the recommended activity activity = decide_activity(temp, humid) # Display the result print(f"Recommended activity: {activity}") if __name__ == "__main__": main() Recommended activity: Play tennis # Jack is a teacher who needs a program that helps him to compile 8th class results. He # has five subjects (English, Maths, Chemistry, Social Science, and Biology) marked in detail. # Program asks the user to enter five subjects' marks, including student name and displays # the total marks, percentage, grade (by percentage), and student name. Every subject has a # total of 100 marks. Grading policy details are mentioned below. # Percentage Grade # 90-100 percentage A+ # 80-90 percentage A # 70-80 percentage B+ # 60-70 percentage B # 50-60 percentage C # 40-50 percentage D # Below 40 percentage F # Your task is to create 2 functions. # 1. float calculateAverage(float marksEnglish, float marksMaths, float # marksChemistry, float marksSocialScience, float marksBiology) # 2. string calculateGrade(float average) # 1st function should take all the marks and then return the average of the marks then 2nd # function should take the average and then return the grade as string def calculateAverage(marksEnglish, marksMaths, marksChemistry, marksSocialScience, marksBiology): # Sum of marks divided by the number of subjects return (marksEnglish + marksMaths + marksChemistry + marksSocialScience + marksBiology) / 5 def calculateGrade(average): # Grading policy based on percentage/average if average >= 90: return "A+" elif average >= 80: return "A" elif average >= 70: return "B+" elif average >= 60: return "B" elif average >= 50: return "C" elif average >= 40: return "D" else : return "F" def main(): # User Inputs matching the image scenario name = input("Enter student name: ") eng = float(input("Enter marks for English: ")) math = float(input("Enter marks for Maths: ")) chem = float(input("Enter marks for Chemistry: ")) soc = float(input("Enter marks for Social Science: ")) bio = float(input("Enter marks for Biology: ")) # Perform calculations avg = calculateAverage(eng, math, chem, soc, bio) grade = calculateGrade(avg) In [8]: # Output formatting print(f"\nStudent Name: {name}") print(f"Percentage: {avg}%") print(f"Grade: {grade}") if __name__ == "__main__": main() Student Name: SOHAIB Percentage: 88.6% Grade: A # Write a program that calculates and prints the bill for a cellular telephone company. # The company offers two types of service: regular and premium. Its rates vary, depending on # the type of service. The rates are computed as follows: # Regular service: $10.00 plus the first 50 minutes are free. Charges for over 50 minutes are # $0.20 per minute. # Premium service: $25.00 plus: # • For calls made during the day., the first 75 minutes are free; charges for more than # 75 minutes are $0.10 per minute. # • For calls made during the night, the first 100 minutes are free; charges for more than # 100 minutes are $0.05 per minute. # Your program should prompt the user to enter a service code (type char), and the number # of minutes the service was used. # A service code of r or R means regular service; a service code of p or P means premium # service. Treat any other character as an error. Your program should output the type of # service, the number of minutes the telephone service was used, and the amount due from # the user. # For the premium service, the customer may be using the service during the day and the # night(d or D for day and n or N for the night). Therefore, to calculate the bill, you must ask the # user to input the number of minutes the service was used during the day and the number of # minutes the service was used during the nigh def calculate_bill(): # User inputs matching the image prompts code = input("Enter the service code (R/r for regular, P/p for premium): ") strip() upper() if code == 'R': minutes = int(input("Enter the number of minutes used: ")) service_type = "Regular" # Calculation: $10 base + $0.20 per minute over 50 extra_mins = max(0, minutes - 50) amount_due = 10.00 + (extra_mins * 0.20) elif code == 'P': time = input("Enter time of the call (D/d for day, N/n for night): ") strip() upper() minutes = int(input("Enter the number of minutes used: ")) service_type = "Premium" # Calculation: $25 base fee if time == 'D': # 75 free minutes, $0.10/min after extra_mins = max(0, minutes - 75) amount_due = 25.00 + (extra_mins * 0.10) elif time == 'N': # 100 free minutes, $0.05/min after extra_mins = max(0, minutes - 100) amount_due = 25.00 + (extra_mins * 0.05) else : print("Error: Invalid time code.") return else : print("Error: Invalid service code.") return # Final output display matching the image format print(f"Service Type: {service_type}") print(f"Total Minutes Used: {minutes} minutes") # Formatting amount to remove trailing .0 if possible, matching your $11.4 example formatted_amount = f"{amount_due:g}" print(f"Amount Due: ${formatted_amount}") if __name__ == "__main__": calculate_bill() Service Type: Regular Total Minutes Used: 88 minutes Amount Due: $17.6 # Q7. Write a Python program using dictionary that takes a number as input and counts how # many times each digit (0–9) appears in that number. # The program should then display each digit along with its frequency. # Example: # Input: 1122334455 # Output: # 1 → 2 times # 2 → 2 times In [9]: In [10]: # 3 → 2 times # 4 → 2 times # 5 → 2 times def count_digit_frequency(): # Take input as a string to handle each digit individually num_str = input("Enter a number: ") # Dictionary to store digit counts frequency = {} # Count each digit for digit in num_str: if digit isdigit(): # If digit is already in dictionary, increment; otherwise, set to 1 frequency[digit] = frequency get(digit, 0) + 1 # Display output in sorted order print("Output:") for digit in sorted(frequency keys()): print(f"{digit} → {frequency[digit]} times") if __name__ == "__main__": count_digit_frequency() Output: 4 → 1 times # Q8. You are given a dictionary in which keys are unique, but values may repeat. Your task is # to invert the dictionary, meaning that each value should become a key in the new dictionary, # and each key should become part of a list of keys that originally had that value. # If multiple keys in the original dictionary have the same value, the inverted dictionary must # store those keys together inside a list under that common value. # Given the dictionary: # { "a": 1, "b": 2, "c": 1 } # Both "a" and "c" have the value 1, while "b" has the value 2. # Therefore, the inverted dictionary should group "a" and "c" together: # Output # { # 1: ["a", "c"], # 2: ["b"] # } # Write a Python program that: # 1. Takes the original dictionary as input (fixed or user-defined). # 2. Creates a new dictionary where: # o Each unique value from the original dictionary becomes a key. # o The corresponding keys from the original dictionary are stored in a list. # 3. Displays the inverted dictionary def invert_dictionary(original): inverted_dict = {} for key, value in original items(): # If the value isn't a key yet, initialize it with an empty list if value not in inverted_dict: inverted_dict[value] = [] # Append the original key to the list associated with this value inverted_dict[value] append(key) return inverted_dict # Test Data original_data = { "a": 1, "b": 2, "c": 1 } # Process and Display result = invert_dictionary(original_data) print("Original Dictionary:", original_data) print("Inverted Dictionary:", result) Original Dictionary: {'a': 1, 'b': 2, 'c': 1} Inverted Dictionary: {1: ['a', 'c'], 2: ['b']} # Q9. You are required to write a Python function that determines whether a given list of # numbers is sorted in ascending order. # A list is considered sorted in ascending order if every element is less than or equal to the # next element. # Create a function that: # 1. Takes a list of numbers as input (either from the user or predefined). # 2. Checks whether the list is sorted in ascending order. # 3. Returns or prints: # o "The list is sorted" if all elements follow ascending order. # o "The list is not sorted" otherwise. # Input: # [1, 2, 3, 4, 5] # Output: # The list is sorted # Input: In [11]: In [12]: # [3, 1, 4, 2] # Output: # The list is not sorted def is_sorted(numbers): # Iterate through the list up to the second-to-last element for i in range(len(numbers) - 1): # If any element is greater than the next, it's not sorted if numbers[i] > numbers[i + 1]: return "The list is not sorted" return "The list is sorted" # Test cases list1 = [1, 2, 3, 4, 5] list2 = [3, 1, 4, 2] print(f"Input: {list1}\nOutput: {is_sorted(list1)}") print(f"Input: {list2}\nOutput: {is_sorted(list2)}") Input: [1, 2, 3, 4, 5] Output: The list is sorted Input: [3, 1, 4, 2] Output: The list is not sorted # You are given a list containing integer values. Your task is to separate these integers # into two new lists based on whether they are even or odd. # Write a Python program that: # 1. Takes a list of integers (either user input or predefined). # 2. Creates two new lists: # o Even List → contains all numbers divisible by 2 # o Odd List → contains all numbers NOT divisible by 2 # 3. Prints both lists separately. # Definition Reminder # • A number is even if: # • number % 2 == 0 # • A number is odd if: # • number % 2 != 0 # Input List: # [10, 21, 4, 45, 66, 93] # Output: # Even numbers: [10, 4, 66] # Odd numbers: [21, 45, 93 def separate_even_odd(numbers): even_list = [] odd_list = [] for num in numbers: # Check if the number is divisible by 2 if num % 2 == 0: even_list append(num) else : odd_list append(num) print(f"Even numbers: {even_list}") print(f"Odd numbers: {odd_list}") # Input List input_list = [10, 21, 4, 45, 66, 93] # Execute separate_even_odd(input_list) Even numbers: [10, 4, 66] Odd numbers: [21, 45, 93] In [13]: In [ ]: