Solutions to Programming Exercises - 002

Python Programming Exercises 002: 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. You can also view the solutions on GitHub: View on GitHub.

Below are 20 Python programming exercises to help you practice and enhance your skills. Each exercise includes a hint to guide you. Try to solve them on your own before looking at the solutions. File names for saving your work are specified in each exercise.

Exercise 1: Print Odd Numbers

Filename: print_odd_numbers.py

Write a program to print all odd numbers from 1 to 50.

Hint: Use a for loop with a step of 2 starting from 1.

# Exercise 1: Print Odd Numbers
# Filename: print_odd_numbers.py
for number in range(1, 51, 2):
    print(number)

Explanation: The program uses a for loop with range(1, 51, 2), which generates numbers from 1 to 50 with a step of 2, effectively listing all odd numbers. It then prints each number in the loop.

---

Exercise 2: Sum of Even Numbers

Filename: sum_even_numbers.py

Write a program to calculate the sum of all even numbers from 1 to 100.

Hint: Use a for loop and check if each number is even before adding it to the sum.

# Exercise 2: Sum of Even Numbers
# Filename: sum_even_numbers.py
total = 0
for number in range(1, 101):
    if number % 2 == 0:
        total += number
print(f"The sum of even numbers from 1 to 100 is {total}")

Explanation: The program initializes a variable total to 0. It then iterates from 1 to 100, checks if a number is even using number % 2 == 0, and adds it to total if it is. Finally, it prints the sum of all even numbers.

---

Exercise 3: Factorial Calculation

Filename: factorial.py

Write a program to compute the factorial of a given number.

Hint: Use a while loop or recursion.

# Exercise 3: Factorial Calculation
# Filename: factorial.py
number = int(input("Enter a number: "))
factorial = 1
if number < 0:
    print("Factorial does not exist for negative numbers.")
elif number == 0:
    print("The factorial of 0 is 1.")
else:
    for i in range(1, number + 1):
        factorial *= i
    print(f"The factorial of {number} is {factorial}")

Explanation: The program checks if the input number is negative, zero, or positive. For positive numbers, it calculates the factorial by multiplying all integers from 1 to the input number using a for loop.

---

Exercise 4: Multiplication Table

Filename: multiplication_table.py

Write a program to print the multiplication table of a number entered by the user.

Hint: Use a for loop from 1 to 10.

# Exercise 4: Multiplication Table
# Filename: multiplication_table.py
number = int(input("Enter a number: "))
print(f"Multiplication Table of {number}:")
for i in range(1, 11):
    print(f"{number} x {i} = {number * i}")

Explanation: The program prompts the user for a number and then uses a for loop to iterate from 1 to 10, printing the product of the input number and the loop counter each time.

---

Exercise 5: Fibonacci Sequence

Filename: fibonacci_sequence.py

Write a program to generate the first 20 numbers of the Fibonacci sequence.

Hint: The next number is the sum of the previous two numbers.

# Exercise 5: Fibonacci Sequence
# Filename: fibonacci_sequence.py
n_terms = 20
n1, n2 = 0, 1
count = 0
print("Fibonacci sequence:")
while count < n_terms:
    print(n1)
    nth = n1 + n2
    n1 = n2
    n2 = nth
    count += 1

Explanation: The program initializes the first two terms of the Fibonacci sequence, n1 and n2. It then uses a while loop to generate and print the next terms by summing the previous two terms, repeating this process until 20 numbers are generated.

---

Exercise 6: Reverse a String

Filename: reverse_string.py

Write a program to reverse a string entered by the user.

Hint: Use slicing or a for loop.

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

Explanation: The program takes input from the user and uses slicing with a step of -1 to reverse the string. It then prints the reversed string.

---

Exercise 7: Count Vowels

Filename: count_vowels.py

Write a program to count the number of vowels in a string entered by the user.

Hint: Iterate through the string and check if each character is a vowel.

# Exercise 7: Count Vowels
# Filename: count_vowels.py
user_string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in user_string:
    if char in vowels:
        count += 1
print(f"Number of vowels in the string: {count}")

Explanation: The program defines a string of vowels and initializes a counter. It iterates over each character in the user's input string, increments the counter if the character is a vowel, and finally prints the total count.

---

Exercise 8: Palindrome Check

Filename: palindrome_check.py

Write a program to check if a string entered by the user is a palindrome.

Hint: A palindrome reads the same backward as forward.

# Exercise 8: Palindrome Check
# Filename: palindrome_check.py
user_string = input("Enter a string: ")
reversed_string = user_string[::-1]
if user_string == reversed_string:
    print(f"'{user_string}' is a palindrome.")
else:
    print(f"'{user_string}' is not a palindrome.")

Explanation: The program reverses the input string and compares it to the original. If they are the same, it confirms that the string is a palindrome.

---

Exercise 9: Find the Largest Number

Filename: find_largest.py

Write a program to find the largest number in a list of numbers entered by the user.

Hint: Use a for loop to compare each number.

# Exercise 9: Find the Largest Number
# Filename: find_largest.py
numbers = input("Enter numbers separated by spaces: ").split()
numbers = [float(num) for num in numbers]
largest = numbers[0]
for num in numbers:
    if num > largest:
        largest = num
print(f"The largest number is: {largest}")

Explanation: The program takes a space-separated list of numbers from the user, converts them to floats, and initializes the largest number as the first element. It then iterates through the list, updating the largest number when a larger one is found.

---

Exercise 10: Prime Number Check

Filename: prime_check.py

Write a program to check if a number entered by the user is a prime number.

Hint: A prime number is only divisible by 1 and itself.

# Exercise 10: Prime Number Check
# Filename: prime_check.py
number = int(input("Enter a number: "))
if number > 1:
    for i in range(2, int(number ** 0.5) + 1):
        if number % i == 0:
            print(f"{number} is not a prime number.")
            break
    else:
        print(f"{number} is a prime number.")
else:
    print(f"{number} is not a prime number.")

Explanation: The program checks if the number is greater than 1 and then tests divisibility up to the square root of the number. If a divisor is found, it declares the number as not prime; otherwise, it confirms it is prime.

---

Exercise 11: Generate a List of Prime Numbers

Filename: list_primes.py

Write a program to generate a list of all prime numbers up to 100.

Hint: Use nested loops to check each number.

# Exercise 11: Generate a List of Prime Numbers
# Filename: list_primes.py
primes = []
for num in range(2, 101):
    is_prime = True
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        primes.append(num)
print("Prime numbers up to 100:")
print(primes)

Explanation: The program iterates over numbers from 2 to 100 and checks each for primality using a nested loop. If a number is prime, it's added to the primes list, which is printed at the end.

---

Exercise 12: Convert Celsius to Fahrenheit

Filename: celsius_to_fahrenheit.py

Write a program to convert a temperature from Celsius to Fahrenheit.

Hint: Use the formula F = C * 9/5 + 32.

# Exercise 12: 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 takes the temperature in Celsius from the user, applies the conversion formula, and prints the result in Fahrenheit.

---

Exercise 13: Calculate Distance Traveled

Filename: distance_traveled.py

Write a program to calculate the distance traveled by a projectile given initial velocity and time.

Hint: Use the formula d = vt.

# Exercise 13: Calculate Distance Traveled
# Filename: distance_traveled.py
velocity = float(input("Enter initial velocity (m/s): "))
time = float(input("Enter time (s): "))
distance = velocity * time
print(f"Distance traveled: {distance} meters")

Explanation: The program asks the user for the initial velocity and time, calculates the distance using the formula d = vt, and displays the result.

---

Exercise 14: Quadratic Equation Roots

Filename: quadratic_roots.py

Write a program to find the roots of a quadratic equation ax2 + bx + c = 0.

Hint: Use the quadratic formula x = (-b ± sqrt(b² - 4ac)) / 2a.

# Exercise 14: Quadratic Equation Roots
# Filename: quadratic_roots.py
import math

a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))

discriminant = b**2 - 4*a*c

if discriminant > 0:
    root1 = (-b + math.sqrt(discriminant)) / (2*a)
    root2 = (-b - math.sqrt(discriminant)) / (2*a)
    print(f"The roots are real and different: {root1}, {root2}")
elif discriminant == 0:
    root = -b / (2*a)
    print(f"The root is real and repeated: {root}")
else:
    real_part = -b / (2*a)
    imag_part = math.sqrt(-discriminant) / (2*a)
    print(f"The roots are complex and different: {real_part} ± {imag_part}i")

Explanation: The program calculates the discriminant to determine the nature of the roots and then computes them accordingly, handling real and complex solutions.

---

Exercise 15: Calculate Compound Interest

Filename: compound_interest.py

Write a program to calculate compound interest given principal, rate, and time.

Hint: Use the formula A = P(1 + r/n)^(nt).

# Exercise 15: Calculate Compound Interest
# Filename: compound_interest.py
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual interest rate (in %): ")) / 100
time = float(input("Enter the time in years: "))
n = int(input("Enter the number of times interest is compounded per year: "))

amount = principal * (1 + rate / n) ** (n * time)
interest = amount - principal

print(f"The compound interest is: {interest:.2f}")
print(f"The total amount after {time} years is: {amount:.2f}")

Explanation: The program collects the necessary inputs, calculates the compound interest using the provided formula, and prints both the interest earned and the total amount.

---

Exercise 16: Generate a Sine Wave Table

Filename: sine_wave.py

Write a program to generate a table of sine values for angles from 0 to 360 degrees.

Hint: Use the math.sin() function and convert degrees to radians using math.radians().

# Exercise 16: Generate a Sine Wave Table
# Filename: sine_wave.py
import math

print("Angle (degrees)\tSine Value")
for angle in range(0, 361, 15):
    sine_value = math.sin(math.radians(angle))
    print(f"{angle}\t\t{round(sine_value, 4)}")

Explanation: The program iterates over angles from 0 to 360 degrees in 15-degree increments, calculates the sine value for each angle, and prints a formatted table.

---

Exercise 17: Calculate Area of Circle

Filename: area_circle.py

Write a program to calculate the area of a circle given its radius.

Hint: Use the formula A = πr².

# Exercise 17: Calculate Area of Circle
# Filename: area_circle.py
import math

radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
print(f"The area of the circle is: {area:.2f}")

Explanation: The program takes the radius input, computes the area using the formula with math.pi, and prints the result rounded to two decimal places.

---

Exercise 18: Calculate Projectile Motion

Filename: projectile_motion.py

Write a program to calculate the maximum height and range of a projectile given initial velocity and angle of launch.

Hint: Use the formulas H = (v² * sin²θ) / (2g) and R = (v² * sin(2θ)) / g.

# Exercise 18: Calculate Projectile Motion
# Filename: projectile_motion.py
import math

velocity = float(input("Enter the initial velocity (m/s): "))
angle_deg = float(input("Enter the angle of launch (degrees): "))
g = 9.81  # Acceleration due to gravity (m/s^2)

angle_rad = math.radians(angle_deg)

max_height = (velocity ** 2 * math.sin(angle_rad) ** 2) / (2 * g)
range = (velocity ** 2 * math.sin(2 * angle_rad)) / g

print(f"Maximum height: {max_height:.2f} meters")
print(f"Range: {range:.2f} meters")

Explanation: The program converts the launch angle to radians, calculates the maximum height and range using the provided formulas, and prints the results.

---

Exercise 19: Calculate Sine and Cosine Values

Filename: sine_cosine.py

Write a program to calculate and print the sine and cosine values for angles from 0 to 360 degrees.

Hint: Use the math.sin() and math.cos() functions.

# Exercise 19: Calculate Sine and Cosine Values
# Filename: sine_cosine.py
import math

print("Angle\tSine\t\tCosine")
for angle in range(0, 361, 15):
    rad = math.radians(angle)
    sine = round(math.sin(rad), 4)
    cosine = round(math.cos(rad), 4)
    print(f"{angle}\t{sine}\t\t{cosine}")

Explanation: Similar to Exercise 16, but this program calculates both sine and cosine values for each angle and prints them in a table format.

---

Exercise 20: Implement a Basic Calculator

Filename: basic_calculator.py

Write a program to implement a basic calculator that can perform addition, subtraction, multiplication, and division.

Hint: Use functions for each operation and a loop to repeatedly ask for user input until they choose to exit.

# Exercise 20: Implement a Basic Calculator
# Filename: basic_calculator.py
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y != 0:
        return x / y
    else:
        return "Cannot divide by zero."

def calculator():
    print("Basic Calculator")
    while True:
        print("\nSelect operation:")
        print("1. Add")
        print("2. Subtract")
        print("3. Multiply")
        print("4. Divide")
        print("5. Exit")

        choice = input("Enter choice (1/2/3/4/5): ")

        if choice == '5':
            print("Exiting the calculator.")
            break

        if choice in ('1', '2', '3', '4'):
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))

            if choice == '1':
                print(f"Result: {add(num1, num2)}")
            elif choice == '2':
                print(f"Result: {subtract(num1, num2)}")
            elif choice == '3':
                print(f"Result: {multiply(num1, num2)}")
            elif choice == '4':
                print(f"Result: {divide(num1, num2)}")
        else:
            print("Invalid input. Please enter a number between 1 and 5.")

calculator()

Explanation: The program defines functions for each arithmetic operation and uses a while loop to continuously prompt the user for an operation until they choose to exit.

---

Key Takeaways

These exercises cover a wide range of fundamental programming concepts in Python, including loops, conditionals, functions, and mathematical computations. Working through these problems helps solidify understanding and prepares you for more advanced programming challenges. Remember to test your code thoroughly and consider edge cases to ensure accuracy.