Programming Exercises - 001 : Solutions

Programming Exercises - 001: Input-Output, Variables, Expressions Solutions

Below are the solutions to the 20 Python programming exercises provided earlier. Please attempt to solve the problems on your own before referring to these solutions.

1. Simple Greeting

Question: Write a Python script named simple_greeting.py that asks the user for their name and then prints a greeting message.

Hint: Use the input() function to get the user's name and the print() function to display the message.

# Exercise 1: Simple Greeting
# Filename: simple_greeting.py
name = input("Enter your name: ")
print(f"Hello, {name}! Welcome!")

Explanation: The program prompts the user to enter their name using input() and then uses an f-string to print a personalized greeting.

---

2. Addition of Two Numbers

Question: Create a Python script named add_two_numbers.py that asks the user to enter two numbers and then prints their sum.

Hint: Use the input() function to read the numbers as strings and int() to convert them to integers before adding.

# Exercise 2: Addition of Two Numbers
# Filename: add_two_numbers.py
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
sum = num1 + num2
print(f"The sum of {num1} and {num2} is {sum}.")

Explanation: The program reads two numbers from the user, converts them to integers using int(), adds them, and then prints the result.

---

3. Calculate the Square of a Number

Question: Write a Python script named calculate_square.py that reads a number from the user and prints its square.

Hint: To find the square, multiply the number by itself.

# Exercise 3: Calculate the Square of a Number
# Filename: calculate_square.py
number = float(input("Enter a number: "))
square = number ** 2
print(f"The square of {number} is {square}.")

Explanation: The program reads a number from the user, calculates its square using the exponentiation operator **, and prints the result.

---

4. Check for Even or Odd Number

Question: Create a Python script named even_or_odd.py that checks whether a given number is even or odd.

Hint: Use the modulus operator % to determine if the number is divisible by 2.

# Exercise 4: Check for Even or Odd Number
# Filename: even_or_odd.py
number = int(input("Enter an integer: "))
if number % 2 == 0:
    print(f"{number} is an even number.")
else:
    print(f"{number} is an odd number.")

Explanation: The program checks if the number modulo 2 equals 0 to determine if it's even; otherwise, it's odd.

---

5. Convert Celsius to Fahrenheit

Question: Write a Python script named celsius_to_fahrenheit.py that converts a temperature given in Celsius to Fahrenheit.

Hint: Use the formula F = (C * 9/5) + 32 to convert Celsius to Fahrenheit.

# Exercise 5: Convert Celsius to Fahrenheit
# Filename: celsius_to_fahrenheit.py
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F.")

Explanation: The program applies the conversion formula to convert Celsius to Fahrenheit and prints the result.

---

6. Calculate the Area of a Rectangle

Question: Create a Python script named area_rectangle.py that calculates the area of a rectangle given its length and width.

Hint: The area of a rectangle is calculated using the formula Area = length * width.

# Exercise 6: Calculate the Area of a Rectangle
# Filename: area_rectangle.py
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print(f"The area of the rectangle is {area} square units.")

Explanation: The program multiplies the length and width to calculate the area and prints the result.

---

7. Calculate Simple Interest

Question: Write a Python script named simple_interest.py that calculates simple interest using the formula SI = (P * R * T) / 100, where P is the principal amount, R is the rate of interest, and T is the time period.

Hint: Read the values of P, R, and T from the user.

# Exercise 7: Calculate Simple Interest
# Filename: simple_interest.py
P = float(input("Enter the principal amount: "))
R = float(input("Enter the rate of interest (%): "))
T = float(input("Enter the time period (years): "))
SI = (P * R * T) / 100
print(f"The simple interest is {SI}.")

Explanation: The program calculates simple interest using the provided formula and prints the result.

---

8. Find the Largest of Three Numbers

Question: Create a Python script named largest_of_three.py that reads three numbers from the user and prints the largest one.

Hint: Use the if-elif-else statements to compare the three numbers.

# Exercise 8: Find the Largest of Three Numbers
# Filename: largest_of_three.py
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

if (num1 >= num2) and (num1 >= num3):
    largest = num1
elif (num2 >= num1) and (num2 >= num3):
    largest = num2
else:
    largest = num3

print(f"The largest number is {largest}.")

Explanation: The program compares the three numbers using conditional statements to determine the largest and prints it.

---

9. Check if a Number is Positive, Negative, or Zero

Question: Write a Python script named check_number.py that reads a number from the user and checks whether it is positive, negative, or zero.

Hint: Use if, elif, and else to handle the different cases.

# Exercise 9: Check if a Number is Positive, Negative, or Zero
# Filename: check_number.py
number = float(input("Enter a number: "))

if number > 0:
    print(f"{number} is positive.")
elif number < 0:
    print(f"{number} is negative.")
else:
    print("The number is zero.")

Explanation: The program checks the sign of the number and prints the appropriate message.

---

10. Calculate the Perimeter of a Rectangle

Question: Create a Python script named perimeter_rectangle.py that calculates the perimeter of a rectangle given its length and width.

Hint: The perimeter of a rectangle is calculated using the formula Perimeter = 2 * (length + width).

# Exercise 10: Calculate the Perimeter of a Rectangle
# Filename: perimeter_rectangle.py
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
perimeter = 2 * (length + width)
print(f"The perimeter of the rectangle is {perimeter} units.")

Explanation: The program calculates the perimeter using the provided formula and prints the result.

---

11. Convert Kilometers to Miles

Question: Write a Python script named km_to_miles.py that converts a distance given in kilometers to miles.

Hint: Use the conversion factor 1 kilometer = 0.621371 miles.

# Exercise 11: Convert Kilometers to Miles
# Filename: km_to_miles.py
kilometers = float(input("Enter distance in kilometers: "))
miles = kilometers * 0.621371
print(f"{kilometers} kilometers is equal to {miles} miles.")

Explanation: The program multiplies the distance in kilometers by the conversion factor to get miles and prints the result.

---

12. Swap Two Variables

Question: Create a Python script named swap_variables.py that swaps the values of two variables.

Hint: Use a temporary variable to hold one of the values during the swap.

# Exercise 12: Swap Two Variables
# Filename: swap_variables.py
a = input("Enter the value of a: ")
b = input("Enter the value of b: ")

# Swapping the values
temp = a
a = b
b = temp

print(f"After swapping:\na = {a}\nb = {b}")

Explanation: The program uses a temporary variable to swap the values of a and b and then prints the new values.

---

13. Calculate the Area of a Circle

Question: Write a Python script named area_circle.py that calculates the area of a circle given its radius.

Hint: Use the formula Area = 3.14159 * radius * radius for the calculation.

# Exercise 13: Calculate the Area of a Circle
# Filename: area_circle.py
radius = float(input("Enter the radius of the circle: "))
area = 3.14159 * radius ** 2
print(f"The area of the circle is {area} square units.")

Explanation: The program calculates the area using the provided formula and prints the result.

---

14. Calculate the Average of Three Numbers

Question: Create a Python script named average_three_numbers.py that reads three numbers from the user and prints their average.

Hint: Calculate the average using the formula Average = (num1 + num2 + num3) / 3.

# Exercise 14: Calculate the Average of Three Numbers
# Filename: average_three_numbers.py
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
average = (num1 + num2 + num3) / 3
print(f"The average of the three numbers is {average}.")

Explanation: The program calculates the average by summing the numbers and dividing by 3, then prints the result.

---

15. Check if a Year is a Leap Year

Question: Write a Python script named leap_year.py that checks if a given year is a leap year.

Hint: A year is a leap year if it is divisible by 4, but not by 100 unless it is also divisible by 400.

# Exercise 15: Check if a Year is a Leap Year
# Filename: leap_year.py
year = int(input("Enter a year: "))

if (year % 4 == 0):
    if (year % 100 != 0) or (year % 400 == 0):
        print(f"{year} is a leap year.")
    else:
        print(f"{year} is not a leap year.")
else:
    print(f"{year} is not a leap year.")

Explanation: The program checks the conditions for a leap year using nested if statements and prints the appropriate message.

---

16. Convert Hours and Minutes to Minutes

Question: Create a Python script named time_to_minutes.py that converts a given time in hours and minutes to total minutes.

Hint: Multiply the hours by 60 and add the minutes to get the total minutes.

# Exercise 16: Convert Hours and Minutes to Minutes
# Filename: time_to_minutes.py
hours = int(input("Enter hours: "))
minutes = int(input("Enter minutes: "))
total_minutes = hours * 60 + minutes
print(f"The total time in minutes is {total_minutes} minutes.")

Explanation: The program calculates the total minutes by converting hours to minutes and adding the remaining minutes.

---

17. Reverse a String

Question: Write a Python script named reverse_string.py that reads a string from the user and prints it in reverse.

Hint: You can reverse a string using slicing like this: reversed_string = string[::-1].

# Exercise 17: Reverse a String
# Filename: reverse_string.py
string = input("Enter a string: ")
reversed_string = string[::-1]
print(f"The reversed string is: {reversed_string}")

Explanation: The program reverses the input string using slicing and prints the reversed string.

---

18. Calculate the Volume of a Cube

Question: Create a Python script named volume_cube.py that calculates the volume of a cube given its side length.

Hint: Use the formula Volume = side ** 3 for the calculation.

# Exercise 18: Calculate the Volume of a Cube
# Filename: volume_cube.py
side = float(input("Enter the side length of the cube: "))
volume = side ** 3
print(f"The volume of the cube is {volume} cubic units.")

Explanation: The program calculates the volume by raising the side length to the power of 3 and prints the result.

---

19. Check if a Number is Divisible by Another

Question: Write a Python script named divisibility_check.py that checks if one number is divisible by another.

Hint: Use the modulus operator % to check divisibility.

# Exercise 19: Check if a Number is Divisible by Another
# Filename: divisibility_check.py
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))

if num2 == 0:
    print("Cannot divide by zero.")
elif num1 % num2 == 0:
    print(f"{num1} is divisible by {num2}.")
else:
    print(f"{num1} is not divisible by {num2}.")

Explanation: The program checks for division by zero and then uses the modulus operator to determine divisibility, printing the appropriate message.

---

20. Convert Days to Hours, Minutes, and Seconds

Question: Create a Python script named days_to_hms.py that converts a given number of days into hours, minutes, and seconds.

Hint: Use the conversion factors: 1 day = 24 hours, 1 hour = 60 minutes, and 1 minute = 60 seconds.

# Exercise 20: Convert Days to Hours, Minutes, and Seconds
# Filename: days_to_hms.py
days = int(input("Enter the number of days: "))
hours = days * 24
minutes = hours * 60
seconds = minutes * 60

print(f"{days} days is equal to:")
print(f"{hours} hours")
print(f"{minutes} minutes")
print(f"{seconds} seconds")

Explanation: The program performs sequential conversions from days to hours, minutes, and seconds, printing each result.

---

Key Takeaways

These exercises help you practice basic Python concepts such as variables, data types, operators, expressions, and basic input/output. By working through these problems, you strengthen your foundational understanding, which is essential for tackling more advanced programming challenges.