ETP Questions
INT108
Unit 1: Temperature Converter
Write a program that takes a temperature in Celsius as input (float) and converts it to Fahrenheit using the formula: .
Input Format:
25.0
Output Format:
77.0
# Read input as float
celsius = float(input())
# Apply formula
fahrenheit = (celsius * 9/5) + 32
# Print result
print(fahrenheit)
Unit 1: Variable Swapping
Write a program to swap two integer inputs without using a temporary variable (using Python's tuple assignment).
Input Format:
10
20
Output Format:
a: 20
b: 10
a = int(input())
b = int(input())
# Pythonic swap
a, b = b, a
print(f"a: {a}")
print(f"b: {b}")
Unit 1: Time Converter
Write a program that takes a total number of minutes as input and converts it into Hours and Minutes using floor division (//) and modulus (%).
Input Format:
130
Output Format:
2 Hours and 10 Minutes
total_minutes = int(input())
# Floor division for hours
hours = total_minutes // 60
# Modulus for remaining minutes
minutes = total_minutes % 60
print(f"{hours} Hours and {minutes} Minutes")
Unit 1: String Repetition and Concatenation
Write a program that takes a string word and a number n. Print the word repeated n times, followed by the string "!!!", all concatenated together.
Input Format:
Go
3
Output Format:
GoGoGo!!!
word = input()
n = int(input())
# String repetition using *
repeated = word * n
# Concatenation using +
result = repeated + "!!!"
print(result)
Unit 2: Leap Year Checker
Write a program that takes a year as input and checks if it is a leap year. A year is a leap year if it is divisible by 4, except for end-of-century years, which must be divisible by 400.
Input Format:
2000
Output Format:
Leap Year
year = int(input())
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap Year")
else:
print("Not a Leap Year")
Unit 2: Sum of Digits
Write a program using a while loop to calculate the sum of digits of a given integer.
Input Format:
12345
Output Format:
15
num = int(input())
total = 0
while num > 0:
digit = num % 10 # Extract last digit
total += digit
num = num // 10 # Remove last digit
print(total)
Unit 2: Prime Number Checker
Write a program that checks if a given number n is a prime number using a for loop.
Input Format:
7
Output Format:
Prime
n = int(input())
if n <= 1:
print("Not Prime")
else:
is_prime = True
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
is_prime = False
break
if is_prime:
print("Prime")
else:
print("Not Prime")
Unit 2: Random Dice Simulation
Write a program that simulates rolling a 6-sided die. Import the random module and print a random integer between 1 and 6 (inclusive).
Input Format:
(No input)
Output Format:
(Any number between 1 and 6, e.g., 4)
import random
# Generate random integer between 1 and 6 inclusive
roll = random.randint(1, 6)
print(roll)
Unit 3: Calculator Function
Define a function calculate(a, b, operator) that takes two numbers and a string operator ('+', '-', '*', '/') and returns the result. Handle division by zero by returning None.
Input Format:
10
5
+
Output Format:
15
def calculate(a, b, op):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
if b == 0: return None
return a / b
else:
return None
a = int(input())
b = int(input())
op = input()
print(calculate(a, b, op))
Unit 3: Recursive Factorial
Write a recursive function factorial(n) that calculates the factorial of a number.
Input Format:
5
Output Format:
120
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
n = int(input())
print(factorial(n))
Unit 3: Hypotenuse Calculator
Write a function that uses math.sqrt and math.pow to calculate the length of the hypotenuse of a right triangle given sides a and b.
Input Format:
3
4
Output Format:
5.0
import math
def hypotenuse(a, b):
# c = sqrt(a^2 + b^2)
return math.sqrt(math.pow(a, 2) + math.pow(b, 2))
a = float(input())
b = float(input())
print(hypotenuse(a, b))
Unit 3: Sum of Arbitrary Arguments
Write a function sum_all(*args) that takes any number of integer arguments and returns their sum.
Input Format:
1 2 3 4 5
Output Format:
15
def sum_all(*args):
total = 0
for num in args:
total += num
return total
# Reading input to pass to function
inputs = list(map(int, input().split()))
print(sum_all(*inputs))
Unit 4: Palindrome Check
Write a program that checks if a given string is a palindrome (reads the same forward and backward), ignoring case.
Input Format:
Racecar
Output Format:
True
s = input().lower()
# Check if string equals its reverse
if s == s[::-1]:
print("True")
else:
print("False")
Unit 4: Filter Even Numbers
Write a program that takes a list of integers and returns a new list containing only the even numbers, sorted in ascending order.
Input Format:
9 2 5 4 8 1
Output Format:
[2, 4, 8]
nums = list(map(int, input().split()))
# List comprehension to filter evens
evens = [x for x in nums if x % 2 == 0]
# Sort the result
evens.sort()
print(evens)
Unit 4: Character Frequency
Write a program that counts the frequency of each character in a string and stores it in a dictionary.
Input Format:
hello
Output Format:
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
s = input()
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
print(counts)
Unit 4: Tuple List Sort
Given a list of tuples where each tuple contains (name, age), write a program to sort the list by age (the second element).
Input Format (Hardcoded in solution for demo):
[('Bob', 30), ('Alice', 25), ('Charlie', 35)]
Output Format:
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
# Using lambda function for custom sort key
data = [('Bob', 30), ('Alice', 25), ('Charlie', 35)]
# Sort by index 1 (age)
data.sort(key=lambda x: x[1])
print(data)
Unit 5: Rectangle Class
Create a class Rectangle with an __init__ method that accepts length and width. Add a method area() that returns the area.
Input Format:
10
5
Output Format:
50
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
l = int(input())
w = int(input())
rect = Rectangle(l, w)
print(rect.area())
Unit 5: Bank Account
Create a class Account with a private attribute __balance. Add methods deposit(amount) and get_balance(). Ensure deposit is positive.
Input Format:
1000
500
Output Format:
1500
class Account:
def __init__(self, start_balance):
self.__balance = start_balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
initial = int(input())
dep = int(input())
acc = Account(initial)
acc.deposit(dep)
print(acc.get_balance())
Unit 5: Animal Inheritance
Create a parent class Animal with a method speak() returning "Silence". Create a child class Dog that overrides speak() to return "Bark".
Input Format:
(No input)
Output Format:
Bark
class Animal:
def speak(self):
return "Silence"
class Dog(Animal):
def speak(self):
return "Bark"
d = Dog()
print(d.speak())
Unit 5: Student Class
Create a Student class initialized with name and grades (a list). Add a method average_grade().
Input Format:
Alice
80 90 100
Output Format:
90.0
class Student:
def __init__(self, name, grades):
self.name = name
self.grades = grades
def average_grade(self):
return sum(self.grades) / len(self.grades)
name = input()
grades = list(map(int, input().split()))
s = Student(name, grades)
print(s.average_grade())
Unit 6: Safe Division
Write a program that takes two numbers as input and divides them. Use a try-except block to handle ZeroDivisionError and print "Cannot divide by zero".
Input Format:
10
0
Output Format:
Cannot divide by zero
try:
a = int(input())
b = int(input())
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid Input")
Unit 6: Extract Numbers
Write a program using the re module to find all integers in a given string and print them as a list of strings.
Input Format:
Order 45 items for $200
Output Format:
['45', '200']
import re
text = input()
# \d+ matches one or more digits
numbers = re.findall(r'\d+', text)
print(numbers)
Unit 6: Email Validation
Write a function using Regex to validate if an input string is a basic valid email address (contains characters, an @ symbol, domain, dot, and extension).
Input Format:
test@example.com
Output Format:
Valid
import re
def validate_email(email):
pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
if re.match(pattern, email):
return "Valid"
else:
return "Invalid"
email = input()
print(validate_email(email))
Unit 6: File Write Simulation
Write a code block that opens a file named 'output.txt' in write mode, writes "Hello World" to it, and ensures the file is closed automatically using a context manager.
Input Format:
(No input)
Output Format:
(File output.txt created with content "Hello World")
# Using 'with' automatically closes the file
with open('output.txt', 'w') as f:
f.write("Hello World")
# Verification code (optional for logic)
with open('output.txt', 'r') as f:
print(f.read())