Chapter 2: Beginner Level Exercises
Beginner Level Exercises
Exercise 1: Calculate the Area of a Circle
Concepts:
- Basic arithmetic
- Input/output
- Variables
Description: Write a Python program that takes the radius of a circle as input from the user and calculates its area.
Solution:
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * (radius ** 2)
print(f"The area of the circle with radius {radius} is {area:.2f}")
Exercise 2: Word Frequency Counter
Concepts:
- Strings
- Dictionaries
- Loops
Description: Write a Python program that takes a string as input and counts the frequency of each word in the string.
Solution:
input_string = input("Enter a sentence: ")
words = input_string.lower().split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Word frequencies:", word_count)
Exercise 3: Simple Temperature Converter
Concepts:
- Functions
- Conditional statements
- User input
Description: Write a Python program that converts temperatures between Celsius and Fahrenheit. The program should ask the user for the temperature unit and the value to be converted.
Solution:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
unit = input("Enter the temperature unit (C for Celsius, F for Fahrenheit): ")
value = float(input("Enter the temperature value to be converted: "))
if unit.upper() == "C":
print(f"{value} Celsius is {celsius_to_fahrenheit(value):.2f} Fahrenheit.")
elif unit.upper() == "F":
print(f"{value} Fahrenheit is {fahrenheit_to_celsius(value):.2f} Celsius.")
else:
print("Invalid temperature unit.")
Exercise 4: Odd or Even Number Checker
Concepts:
- Modular arithmetic
- Conditional statements
Description: Write a Python program that checks whether a given number is odd or even.
Solution:
number = int(input("Enter an integer: "))
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
Exercise 5: Simple File Operations
Concepts:
- File I/O
- Exception handling
- String manipulation
Description: Write a Python program that reads a text file, converts its content to uppercase, and writes the result to a new file. If the input file does not exist, display an error message.
Solution:
input_file = input("Enter the name of the input file: ")
output_file = input("Enter the name of the output file: ")
try:
with open(input_file, "r") as infile:
content = infile.read()
uppercase_content = content.upper()
with open(output_file, "w") as outfile:
outfile.write(uppercase_content)
print("The content has been converted to uppercase and saved in the output file.")
except FileNotFoundError:
print(f"The file '{input_file}' does not exist.")
Exercise 6: List of Multiples
Concepts:
- Loops
- Lists
- Arithmetic
Description: Write a Python program that takes a number as input and returns a list of its first 10 multiples.
Solution:
number = int(input("Enter a number: "))
multiples = [number * i for i in range(1, 11)]
print(f"The first 10 multiples of {number} are: {multiples}")
Exercise 7: Palindrome Checker
Concepts:
- Strings
- Conditional statements
- String manipulation
Description: Write a Python program that checks whether a given word or phrase is a palindrome. Ignore spaces, punctuation, and capitalization.
Solution:
import re
input_string = input("Enter a word or phrase: ")
processed_string = re.sub(r'\W+', '', input_string.lower())
reversed_string = processed_string[::-1]
if processed_string == reversed_string:
print(f"'{input_string}' is a palindrome.")
else:
print(f"'{input_string}' is not a palindrome.")
Exercise 8: Simple Interest Calculator
Concepts:
- Arithmetic
- Input/output
- Variables
Description: Write a Python program that calculates the simple interest for a given principal amount, rate of interest, and number of years.
Solution:
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest (percentage): "))
years = int(input("Enter the number of years: "))
interest = principal * rate * years / 100
total_amount = principal + interest
print(f"The simple interest is: {interest:.2f}")
print(f"The total amount after {years} years is: {total_amount:.2f}")
Exercise 9: Fibonacci Sequence Generator
Concepts:
- Loops
- Lists
- Functions
Description: Write a Python program that generates the first n numbers of the Fibonacci sequence, where n is provided by the user.
Solution:
def generate_fibonacci(n):
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
n = int(input("Enter the number of Fibonacci numbers to generate: "))
fibonacci_sequence = generate_fibonacci(n)
print(f"The first {n} Fibonacci numbers are: {fibonacci_sequence}")
Exercise 10: Leap Year Checker
Concepts:
- Conditional statements
- Modular arithmetic
Description: Write a Python program that checks whether a given year is a leap year.
Solution:
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Exercise 11: Prime Number Checker
Concepts:
- Loops
- Conditional statements
- Functions
Description: Write a Python program that checks whether a given number is a prime number.
Solution:
def is_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Exercise 12: Count Vowels in a String
Concepts:
- Strings
- Loops
- Dictionaries
Description: Write a Python program that counts the number of vowels in a given string.
Solution:
input_string = input("Enter a string: ").lower()
vowels = "aeiou"
vowel_count = {}
for char in input_string:
if char in vowels:
if char in vowel_count:
vowel_count[char] += 1
else:
vowel_count[char] = 1
print("Vowel count:", vowel_count)
Exercise 13: Calculate the Factorial of a Number
Concepts:
- Loops
- Conditional statements
- Functions
Description: Write a Python program that calculates the factorial of a given number using loops.
Solution:
def factorial(number):
if number == 0 or number == 1:
return 1
result = 1
for i in range(2, number + 1):
result *= i
return result
number = int(input("Enter a number: "))
print(f"The factorial of {number} is {factorial(number)}")
Exercise 14: Sum of Digits in a Number
Concepts:
- Loops
- Arithmetic
- Strings
Description: Write a Python program that calculates the sum of the digits of a given integer.
Solution:
number = int(input("Enter an integer: "))
sum_of_digits = sum(int(digit) for digit in str(number))
print(f"The sum of the digits of {number} is {sum_of_digits}")
Exercise 15: Caesar Cipher Encoder
Concepts:
- Strings
- Loops
- Modular arithmetic
Description: Write a Python program that implements a simple Caesar cipher. The program should take a string and an integer shift value as input, and return the encoded string.
Solution:
def caesar_cipher(text, shift):
encrypted = []
for char in text:
if char.isalpha():
shift_amount = shift % 26
new_ord = ord(char) + shift_amount
if char.islower():
if new_ord > ord("z"):
new_ord -= 26
else:
if new_ord > ord("Z"):
new_ord -= 26
encrypted.append(chr(new_ord))
else:
encrypted.append(char)
return "".join(encrypted)
text = input("Enter a string: ")
shift = int(input("Enter the shift value: "))
encoded_text = caesar_cipher(text, shift)
print(f"The encoded text is: {encoded_text}")
Exercise 16: Reverse a String
Concepts:
- Strings
- Loops
- Slicing
Description: Write a Python program that reverses a given string.
Solution:
input_string = input("Enter a string: ")
reversed_string = input_string[::-1]
print(f"The reversed string is: {reversed_string}")
Exercise 17: Count Occurrences of a Character
Concepts:
- Strings
- Loops
- Dictionaries
Description: Write a Python program that counts the occurrences of a specific character in a given string.
Solution:
input_string = input("Enter a string: ")
target_char = input("Enter a character to count: ")
count = input_string.lower().count(target_char.lower())
print(f"The character '{target_char}' occurs {count} times in the string.")
Exercise 18: Print the ASCII Value of a Character
Concepts:
- Input/output
- ord() function
Description: Write a Python program that takes a single character as input and prints its ASCII value.
Solution:
char = input("Enter a single character: ")
if len(char) == 1:
print(f"The ASCII value of '{char}' is {ord(char)}")
else:
print("Invalid input. Please enter a single character.")
Exercise 19: Simple Calculator
Concepts:
- Functions
- Input/output
- Conditional statements
Description: Write a Python program that creates a simple calculator that can perform addition, subtraction, multiplication, and division. The program should ask the user for the operation, the two numbers, and then display the result.
Solution:
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):
return x / y
operation = input("Enter the operation (add, subtract, multiply, divide): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operation.lower() == "add":
print(f"The result is: {add(num1, num2)}")
elif operation.lower() == "subtract":
print(f"The result is: {subtract(num1, num2)}")
elif operation.lower() == "multiply":
print(f"The result is: {multiply(num1, num2)}")
elif operation.lower() == "divide":
if num2 == 0:
print("Error: Division by zero is not allowed.")
else:
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid operation.")
Exercise 20: Longest Word in a Sentence
Concepts:
- Strings
- Loops
- String manipulation
Description: Write a Python program that takes a sentence as input and returns the longest word in the sentence.
Solution:
input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
longest_word = ""
max_length = 0
for word in words:
if len(word) > max_length:
max_length = len(word)
longest_word = word
print(f"The longest word in the sentence is: {longest_word}")
Exercise 21: Calculate the Average of Numbers in a List
Concepts:
- Lists
- Loops
- Arithmetic
Description: Write a Python program that calculates the average of a list of numbers.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
average = sum(numbers) / len(numbers)
print(f"The average of the numbers is: {average:.2f}")
Exercise 22: Common Elements in Two Lists
Concepts:
- Lists
- Loops
- Sets
Description: Write a Python program that takes two lists and returns a list of common elements.
Solution:
list1 = input("Enter the first list of numbers separated by spaces: ").split()
list2 = input("Enter the second list of numbers separated by spaces: ").split()
common_elements = list(set(list1) & set(list2))
print(f"The common elements in the two lists are: {common_elements}")
Exercise 23: Find the Smallest and Largest Numbers in a List
Concepts:
- Lists
- Loops
- min() and max() functions
Description: Write a Python program that takes a list of numbers as input and returns the smallest and largest numbers in the list.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
smallest_number = min(numbers)
largest_number = max(numbers)
print(f"The smallest number is: {smallest_number}")
print(f"The largest number is: {largest_number}")
Exercise 24: Remove Duplicates from a List
Concepts:
- Lists
- Sets
- List comprehensions
Description: Write a Python program that takes a list and returns a new list without duplicates.
Solution:
input_list = input("Enter a list of elements separated by spaces: ").split()
unique_list = list(dict.fromkeys(input_list))
print(f"The list without duplicates is: {unique_list}")
Exercise 25: Sorting a List in Ascending and Descending Order
Concepts:
- Lists
- Sorting
Description: Write a Python program that takes a list of numbers as input and returns the same list sorted in ascending and descending order.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
ascending_sorted_list = sorted(numbers)
descending_sorted_list = sorted(numbers, reverse=True)
print(f"The list sorted in ascending order is: {ascending_sorted_list}")
print(f"The list sorted in descending order is: {descending_sorted_list}")
Exercise 26: Square and Cube of Numbers in a List
Concepts:
- Lists
- Loops
- List comprehensions
Description: Write a Python program that takes a list of numbers and returns a new list containing the square and cube of each number.
Solution:
numbers = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
squares_and_cubes = [(x**2, x**3) for x in numbers]
print(f"The squares and cubes of the numbers are: {squares_and_cubes}")
Exercise 27: Count the Number of Words in a Sentence
Concepts:
- Strings
- String manipulation
Description: Write a Python program that takes a sentence as input and counts the number of words in the sentence.
Solution:
input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
word_count = len(words)
print(f"The number of words in the sentence is: {word_count}")
Exercise 28: Swapping Two Variables
Concepts:
- Variables
- Tuples
Description: Write a Python program that takes two variables as input and swaps their values.
Solution:
x = input("Enter the value of x: ")
y = input("Enter the value of y: ")
print(f"Before swapping: x = {x}, y = {y}")
x, y = y, x
print(f"After swapping: x = {x}, y = {y}")
Exercise 29: Distance Between Two Points
Concepts:
- Functions
- Input/output
- Math module
Description: Write a Python program that calculates the distance between two points in a 2D space. The coordinates of the points should be provided by the user.
Solution:
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
x1, y1 = map(float, input("Enter the coordinates of the first point (x1, y1): ").split())
x2, y2 = map(float, input("Enter the coordinates of the second point (x2, y2): ").split())
result = distance(x1, y1, x2, y2)
print(f"The distance between the two points is: {result:.2f}")
Exercise 30: Convert Temperature from Celsius to Fahrenheit and Vice Versa
Concepts:
- Functions
- Input/output
- Conditional statements
Description: Write a Python program that converts temperatures between Celsius and Fahrenheit. The user should provide the temperature value and the unit.
Solution:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
temperature = float(input("Enter the temperature value: "))
unit = input("Enter the unit (C for Celsius, F for Fahrenheit): ")
if unit.upper() == "C":
result = celsius_to_fahrenheit(temperature)
print(f"{temperature} Celsius is equal to {result:.2f} Fahrenheit")
elif unit.upper() == "F":
result = fahrenheit_to_celsius(temperature)
print(f"{temperature} Fahrenheit is equal to {result:.2f} Celsius")
else:
print("Invalid unit. Please enter 'C' for Celsius or 'F' for Fahrenheit.")
Beginner Level Exercises
Exercise 1: Calculate the Area of a Circle
Concepts:
- Basic arithmetic
- Input/output
- Variables
Description: Write a Python program that takes the radius of a circle as input from the user and calculates its area.
Solution:
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * (radius ** 2)
print(f"The area of the circle with radius {radius} is {area:.2f}")
Exercise 2: Word Frequency Counter
Concepts:
- Strings
- Dictionaries
- Loops
Description: Write a Python program that takes a string as input and counts the frequency of each word in the string.
Solution:
input_string = input("Enter a sentence: ")
words = input_string.lower().split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Word frequencies:", word_count)
Exercise 3: Simple Temperature Converter
Concepts:
- Functions
- Conditional statements
- User input
Description: Write a Python program that converts temperatures between Celsius and Fahrenheit. The program should ask the user for the temperature unit and the value to be converted.
Solution:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
unit = input("Enter the temperature unit (C for Celsius, F for Fahrenheit): ")
value = float(input("Enter the temperature value to be converted: "))
if unit.upper() == "C":
print(f"{value} Celsius is {celsius_to_fahrenheit(value):.2f} Fahrenheit.")
elif unit.upper() == "F":
print(f"{value} Fahrenheit is {fahrenheit_to_celsius(value):.2f} Celsius.")
else:
print("Invalid temperature unit.")
Exercise 4: Odd or Even Number Checker
Concepts:
- Modular arithmetic
- Conditional statements
Description: Write a Python program that checks whether a given number is odd or even.
Solution:
number = int(input("Enter an integer: "))
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
Exercise 5: Simple File Operations
Concepts:
- File I/O
- Exception handling
- String manipulation
Description: Write a Python program that reads a text file, converts its content to uppercase, and writes the result to a new file. If the input file does not exist, display an error message.
Solution:
input_file = input("Enter the name of the input file: ")
output_file = input("Enter the name of the output file: ")
try:
with open(input_file, "r") as infile:
content = infile.read()
uppercase_content = content.upper()
with open(output_file, "w") as outfile:
outfile.write(uppercase_content)
print("The content has been converted to uppercase and saved in the output file.")
except FileNotFoundError:
print(f"The file '{input_file}' does not exist.")
Exercise 6: List of Multiples
Concepts:
- Loops
- Lists
- Arithmetic
Description: Write a Python program that takes a number as input and returns a list of its first 10 multiples.
Solution:
number = int(input("Enter a number: "))
multiples = [number * i for i in range(1, 11)]
print(f"The first 10 multiples of {number} are: {multiples}")
Exercise 7: Palindrome Checker
Concepts:
- Strings
- Conditional statements
- String manipulation
Description: Write a Python program that checks whether a given word or phrase is a palindrome. Ignore spaces, punctuation, and capitalization.
Solution:
import re
input_string = input("Enter a word or phrase: ")
processed_string = re.sub(r'\W+', '', input_string.lower())
reversed_string = processed_string[::-1]
if processed_string == reversed_string:
print(f"'{input_string}' is a palindrome.")
else:
print(f"'{input_string}' is not a palindrome.")
Exercise 8: Simple Interest Calculator
Concepts:
- Arithmetic
- Input/output
- Variables
Description: Write a Python program that calculates the simple interest for a given principal amount, rate of interest, and number of years.
Solution:
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest (percentage): "))
years = int(input("Enter the number of years: "))
interest = principal * rate * years / 100
total_amount = principal + interest
print(f"The simple interest is: {interest:.2f}")
print(f"The total amount after {years} years is: {total_amount:.2f}")
Exercise 9: Fibonacci Sequence Generator
Concepts:
- Loops
- Lists
- Functions
Description: Write a Python program that generates the first n numbers of the Fibonacci sequence, where n is provided by the user.
Solution:
def generate_fibonacci(n):
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
n = int(input("Enter the number of Fibonacci numbers to generate: "))
fibonacci_sequence = generate_fibonacci(n)
print(f"The first {n} Fibonacci numbers are: {fibonacci_sequence}")
Exercise 10: Leap Year Checker
Concepts:
- Conditional statements
- Modular arithmetic
Description: Write a Python program that checks whether a given year is a leap year.
Solution:
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Exercise 11: Prime Number Checker
Concepts:
- Loops
- Conditional statements
- Functions
Description: Write a Python program that checks whether a given number is a prime number.
Solution:
def is_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Exercise 12: Count Vowels in a String
Concepts:
- Strings
- Loops
- Dictionaries
Description: Write a Python program that counts the number of vowels in a given string.
Solution:
input_string = input("Enter a string: ").lower()
vowels = "aeiou"
vowel_count = {}
for char in input_string:
if char in vowels:
if char in vowel_count:
vowel_count[char] += 1
else:
vowel_count[char] = 1
print("Vowel count:", vowel_count)
Exercise 13: Calculate the Factorial of a Number
Concepts:
- Loops
- Conditional statements
- Functions
Description: Write a Python program that calculates the factorial of a given number using loops.
Solution:
def factorial(number):
if number == 0 or number == 1:
return 1
result = 1
for i in range(2, number + 1):
result *= i
return result
number = int(input("Enter a number: "))
print(f"The factorial of {number} is {factorial(number)}")
Exercise 14: Sum of Digits in a Number
Concepts:
- Loops
- Arithmetic
- Strings
Description: Write a Python program that calculates the sum of the digits of a given integer.
Solution:
number = int(input("Enter an integer: "))
sum_of_digits = sum(int(digit) for digit in str(number))
print(f"The sum of the digits of {number} is {sum_of_digits}")
Exercise 15: Caesar Cipher Encoder
Concepts:
- Strings
- Loops
- Modular arithmetic
Description: Write a Python program that implements a simple Caesar cipher. The program should take a string and an integer shift value as input, and return the encoded string.
Solution:
def caesar_cipher(text, shift):
encrypted = []
for char in text:
if char.isalpha():
shift_amount = shift % 26
new_ord = ord(char) + shift_amount
if char.islower():
if new_ord > ord("z"):
new_ord -= 26
else:
if new_ord > ord("Z"):
new_ord -= 26
encrypted.append(chr(new_ord))
else:
encrypted.append(char)
return "".join(encrypted)
text = input("Enter a string: ")
shift = int(input("Enter the shift value: "))
encoded_text = caesar_cipher(text, shift)
print(f"The encoded text is: {encoded_text}")
Exercise 16: Reverse a String
Concepts:
- Strings
- Loops
- Slicing
Description: Write a Python program that reverses a given string.
Solution:
input_string = input("Enter a string: ")
reversed_string = input_string[::-1]
print(f"The reversed string is: {reversed_string}")
Exercise 17: Count Occurrences of a Character
Concepts:
- Strings
- Loops
- Dictionaries
Description: Write a Python program that counts the occurrences of a specific character in a given string.
Solution:
input_string = input("Enter a string: ")
target_char = input("Enter a character to count: ")
count = input_string.lower().count(target_char.lower())
print(f"The character '{target_char}' occurs {count} times in the string.")
Exercise 18: Print the ASCII Value of a Character
Concepts:
- Input/output
- ord() function
Description: Write a Python program that takes a single character as input and prints its ASCII value.
Solution:
char = input("Enter a single character: ")
if len(char) == 1:
print(f"The ASCII value of '{char}' is {ord(char)}")
else:
print("Invalid input. Please enter a single character.")
Exercise 19: Simple Calculator
Concepts:
- Functions
- Input/output
- Conditional statements
Description: Write a Python program that creates a simple calculator that can perform addition, subtraction, multiplication, and division. The program should ask the user for the operation, the two numbers, and then display the result.
Solution:
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):
return x / y
operation = input("Enter the operation (add, subtract, multiply, divide): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operation.lower() == "add":
print(f"The result is: {add(num1, num2)}")
elif operation.lower() == "subtract":
print(f"The result is: {subtract(num1, num2)}")
elif operation.lower() == "multiply":
print(f"The result is: {multiply(num1, num2)}")
elif operation.lower() == "divide":
if num2 == 0:
print("Error: Division by zero is not allowed.")
else:
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid operation.")
Exercise 20: Longest Word in a Sentence
Concepts:
- Strings
- Loops
- String manipulation
Description: Write a Python program that takes a sentence as input and returns the longest word in the sentence.
Solution:
input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
longest_word = ""
max_length = 0
for word in words:
if len(word) > max_length:
max_length = len(word)
longest_word = word
print(f"The longest word in the sentence is: {longest_word}")
Exercise 21: Calculate the Average of Numbers in a List
Concepts:
- Lists
- Loops
- Arithmetic
Description: Write a Python program that calculates the average of a list of numbers.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
average = sum(numbers) / len(numbers)
print(f"The average of the numbers is: {average:.2f}")
Exercise 22: Common Elements in Two Lists
Concepts:
- Lists
- Loops
- Sets
Description: Write a Python program that takes two lists and returns a list of common elements.
Solution:
list1 = input("Enter the first list of numbers separated by spaces: ").split()
list2 = input("Enter the second list of numbers separated by spaces: ").split()
common_elements = list(set(list1) & set(list2))
print(f"The common elements in the two lists are: {common_elements}")
Exercise 23: Find the Smallest and Largest Numbers in a List
Concepts:
- Lists
- Loops
- min() and max() functions
Description: Write a Python program that takes a list of numbers as input and returns the smallest and largest numbers in the list.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
smallest_number = min(numbers)
largest_number = max(numbers)
print(f"The smallest number is: {smallest_number}")
print(f"The largest number is: {largest_number}")
Exercise 24: Remove Duplicates from a List
Concepts:
- Lists
- Sets
- List comprehensions
Description: Write a Python program that takes a list and returns a new list without duplicates.
Solution:
input_list = input("Enter a list of elements separated by spaces: ").split()
unique_list = list(dict.fromkeys(input_list))
print(f"The list without duplicates is: {unique_list}")
Exercise 25: Sorting a List in Ascending and Descending Order
Concepts:
- Lists
- Sorting
Description: Write a Python program that takes a list of numbers as input and returns the same list sorted in ascending and descending order.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
ascending_sorted_list = sorted(numbers)
descending_sorted_list = sorted(numbers, reverse=True)
print(f"The list sorted in ascending order is: {ascending_sorted_list}")
print(f"The list sorted in descending order is: {descending_sorted_list}")
Exercise 26: Square and Cube of Numbers in a List
Concepts:
- Lists
- Loops
- List comprehensions
Description: Write a Python program that takes a list of numbers and returns a new list containing the square and cube of each number.
Solution:
numbers = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
squares_and_cubes = [(x**2, x**3) for x in numbers]
print(f"The squares and cubes of the numbers are: {squares_and_cubes}")
Exercise 27: Count the Number of Words in a Sentence
Concepts:
- Strings
- String manipulation
Description: Write a Python program that takes a sentence as input and counts the number of words in the sentence.
Solution:
input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
word_count = len(words)
print(f"The number of words in the sentence is: {word_count}")
Exercise 28: Swapping Two Variables
Concepts:
- Variables
- Tuples
Description: Write a Python program that takes two variables as input and swaps their values.
Solution:
x = input("Enter the value of x: ")
y = input("Enter the value of y: ")
print(f"Before swapping: x = {x}, y = {y}")
x, y = y, x
print(f"After swapping: x = {x}, y = {y}")
Exercise 29: Distance Between Two Points
Concepts:
- Functions
- Input/output
- Math module
Description: Write a Python program that calculates the distance between two points in a 2D space. The coordinates of the points should be provided by the user.
Solution:
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
x1, y1 = map(float, input("Enter the coordinates of the first point (x1, y1): ").split())
x2, y2 = map(float, input("Enter the coordinates of the second point (x2, y2): ").split())
result = distance(x1, y1, x2, y2)
print(f"The distance between the two points is: {result:.2f}")
Exercise 30: Convert Temperature from Celsius to Fahrenheit and Vice Versa
Concepts:
- Functions
- Input/output
- Conditional statements
Description: Write a Python program that converts temperatures between Celsius and Fahrenheit. The user should provide the temperature value and the unit.
Solution:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
temperature = float(input("Enter the temperature value: "))
unit = input("Enter the unit (C for Celsius, F for Fahrenheit): ")
if unit.upper() == "C":
result = celsius_to_fahrenheit(temperature)
print(f"{temperature} Celsius is equal to {result:.2f} Fahrenheit")
elif unit.upper() == "F":
result = fahrenheit_to_celsius(temperature)
print(f"{temperature} Fahrenheit is equal to {result:.2f} Celsius")
else:
print("Invalid unit. Please enter 'C' for Celsius or 'F' for Fahrenheit.")
Beginner Level Exercises
Exercise 1: Calculate the Area of a Circle
Concepts:
- Basic arithmetic
- Input/output
- Variables
Description: Write a Python program that takes the radius of a circle as input from the user and calculates its area.
Solution:
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * (radius ** 2)
print(f"The area of the circle with radius {radius} is {area:.2f}")
Exercise 2: Word Frequency Counter
Concepts:
- Strings
- Dictionaries
- Loops
Description: Write a Python program that takes a string as input and counts the frequency of each word in the string.
Solution:
input_string = input("Enter a sentence: ")
words = input_string.lower().split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Word frequencies:", word_count)
Exercise 3: Simple Temperature Converter
Concepts:
- Functions
- Conditional statements
- User input
Description: Write a Python program that converts temperatures between Celsius and Fahrenheit. The program should ask the user for the temperature unit and the value to be converted.
Solution:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
unit = input("Enter the temperature unit (C for Celsius, F for Fahrenheit): ")
value = float(input("Enter the temperature value to be converted: "))
if unit.upper() == "C":
print(f"{value} Celsius is {celsius_to_fahrenheit(value):.2f} Fahrenheit.")
elif unit.upper() == "F":
print(f"{value} Fahrenheit is {fahrenheit_to_celsius(value):.2f} Celsius.")
else:
print("Invalid temperature unit.")
Exercise 4: Odd or Even Number Checker
Concepts:
- Modular arithmetic
- Conditional statements
Description: Write a Python program that checks whether a given number is odd or even.
Solution:
number = int(input("Enter an integer: "))
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
Exercise 5: Simple File Operations
Concepts:
- File I/O
- Exception handling
- String manipulation
Description: Write a Python program that reads a text file, converts its content to uppercase, and writes the result to a new file. If the input file does not exist, display an error message.
Solution:
input_file = input("Enter the name of the input file: ")
output_file = input("Enter the name of the output file: ")
try:
with open(input_file, "r") as infile:
content = infile.read()
uppercase_content = content.upper()
with open(output_file, "w") as outfile:
outfile.write(uppercase_content)
print("The content has been converted to uppercase and saved in the output file.")
except FileNotFoundError:
print(f"The file '{input_file}' does not exist.")
Exercise 6: List of Multiples
Concepts:
- Loops
- Lists
- Arithmetic
Description: Write a Python program that takes a number as input and returns a list of its first 10 multiples.
Solution:
number = int(input("Enter a number: "))
multiples = [number * i for i in range(1, 11)]
print(f"The first 10 multiples of {number} are: {multiples}")
Exercise 7: Palindrome Checker
Concepts:
- Strings
- Conditional statements
- String manipulation
Description: Write a Python program that checks whether a given word or phrase is a palindrome. Ignore spaces, punctuation, and capitalization.
Solution:
import re
input_string = input("Enter a word or phrase: ")
processed_string = re.sub(r'\W+', '', input_string.lower())
reversed_string = processed_string[::-1]
if processed_string == reversed_string:
print(f"'{input_string}' is a palindrome.")
else:
print(f"'{input_string}' is not a palindrome.")
Exercise 8: Simple Interest Calculator
Concepts:
- Arithmetic
- Input/output
- Variables
Description: Write a Python program that calculates the simple interest for a given principal amount, rate of interest, and number of years.
Solution:
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest (percentage): "))
years = int(input("Enter the number of years: "))
interest = principal * rate * years / 100
total_amount = principal + interest
print(f"The simple interest is: {interest:.2f}")
print(f"The total amount after {years} years is: {total_amount:.2f}")
Exercise 9: Fibonacci Sequence Generator
Concepts:
- Loops
- Lists
- Functions
Description: Write a Python program that generates the first n numbers of the Fibonacci sequence, where n is provided by the user.
Solution:
def generate_fibonacci(n):
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
n = int(input("Enter the number of Fibonacci numbers to generate: "))
fibonacci_sequence = generate_fibonacci(n)
print(f"The first {n} Fibonacci numbers are: {fibonacci_sequence}")
Exercise 10: Leap Year Checker
Concepts:
- Conditional statements
- Modular arithmetic
Description: Write a Python program that checks whether a given year is a leap year.
Solution:
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Exercise 11: Prime Number Checker
Concepts:
- Loops
- Conditional statements
- Functions
Description: Write a Python program that checks whether a given number is a prime number.
Solution:
def is_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Exercise 12: Count Vowels in a String
Concepts:
- Strings
- Loops
- Dictionaries
Description: Write a Python program that counts the number of vowels in a given string.
Solution:
input_string = input("Enter a string: ").lower()
vowels = "aeiou"
vowel_count = {}
for char in input_string:
if char in vowels:
if char in vowel_count:
vowel_count[char] += 1
else:
vowel_count[char] = 1
print("Vowel count:", vowel_count)
Exercise 13: Calculate the Factorial of a Number
Concepts:
- Loops
- Conditional statements
- Functions
Description: Write a Python program that calculates the factorial of a given number using loops.
Solution:
def factorial(number):
if number == 0 or number == 1:
return 1
result = 1
for i in range(2, number + 1):
result *= i
return result
number = int(input("Enter a number: "))
print(f"The factorial of {number} is {factorial(number)}")
Exercise 14: Sum of Digits in a Number
Concepts:
- Loops
- Arithmetic
- Strings
Description: Write a Python program that calculates the sum of the digits of a given integer.
Solution:
number = int(input("Enter an integer: "))
sum_of_digits = sum(int(digit) for digit in str(number))
print(f"The sum of the digits of {number} is {sum_of_digits}")
Exercise 15: Caesar Cipher Encoder
Concepts:
- Strings
- Loops
- Modular arithmetic
Description: Write a Python program that implements a simple Caesar cipher. The program should take a string and an integer shift value as input, and return the encoded string.
Solution:
def caesar_cipher(text, shift):
encrypted = []
for char in text:
if char.isalpha():
shift_amount = shift % 26
new_ord = ord(char) + shift_amount
if char.islower():
if new_ord > ord("z"):
new_ord -= 26
else:
if new_ord > ord("Z"):
new_ord -= 26
encrypted.append(chr(new_ord))
else:
encrypted.append(char)
return "".join(encrypted)
text = input("Enter a string: ")
shift = int(input("Enter the shift value: "))
encoded_text = caesar_cipher(text, shift)
print(f"The encoded text is: {encoded_text}")
Exercise 16: Reverse a String
Concepts:
- Strings
- Loops
- Slicing
Description: Write a Python program that reverses a given string.
Solution:
input_string = input("Enter a string: ")
reversed_string = input_string[::-1]
print(f"The reversed string is: {reversed_string}")
Exercise 17: Count Occurrences of a Character
Concepts:
- Strings
- Loops
- Dictionaries
Description: Write a Python program that counts the occurrences of a specific character in a given string.
Solution:
input_string = input("Enter a string: ")
target_char = input("Enter a character to count: ")
count = input_string.lower().count(target_char.lower())
print(f"The character '{target_char}' occurs {count} times in the string.")
Exercise 18: Print the ASCII Value of a Character
Concepts:
- Input/output
- ord() function
Description: Write a Python program that takes a single character as input and prints its ASCII value.
Solution:
char = input("Enter a single character: ")
if len(char) == 1:
print(f"The ASCII value of '{char}' is {ord(char)}")
else:
print("Invalid input. Please enter a single character.")
Exercise 19: Simple Calculator
Concepts:
- Functions
- Input/output
- Conditional statements
Description: Write a Python program that creates a simple calculator that can perform addition, subtraction, multiplication, and division. The program should ask the user for the operation, the two numbers, and then display the result.
Solution:
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):
return x / y
operation = input("Enter the operation (add, subtract, multiply, divide): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operation.lower() == "add":
print(f"The result is: {add(num1, num2)}")
elif operation.lower() == "subtract":
print(f"The result is: {subtract(num1, num2)}")
elif operation.lower() == "multiply":
print(f"The result is: {multiply(num1, num2)}")
elif operation.lower() == "divide":
if num2 == 0:
print("Error: Division by zero is not allowed.")
else:
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid operation.")
Exercise 20: Longest Word in a Sentence
Concepts:
- Strings
- Loops
- String manipulation
Description: Write a Python program that takes a sentence as input and returns the longest word in the sentence.
Solution:
input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
longest_word = ""
max_length = 0
for word in words:
if len(word) > max_length:
max_length = len(word)
longest_word = word
print(f"The longest word in the sentence is: {longest_word}")
Exercise 21: Calculate the Average of Numbers in a List
Concepts:
- Lists
- Loops
- Arithmetic
Description: Write a Python program that calculates the average of a list of numbers.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
average = sum(numbers) / len(numbers)
print(f"The average of the numbers is: {average:.2f}")
Exercise 22: Common Elements in Two Lists
Concepts:
- Lists
- Loops
- Sets
Description: Write a Python program that takes two lists and returns a list of common elements.
Solution:
list1 = input("Enter the first list of numbers separated by spaces: ").split()
list2 = input("Enter the second list of numbers separated by spaces: ").split()
common_elements = list(set(list1) & set(list2))
print(f"The common elements in the two lists are: {common_elements}")
Exercise 23: Find the Smallest and Largest Numbers in a List
Concepts:
- Lists
- Loops
- min() and max() functions
Description: Write a Python program that takes a list of numbers as input and returns the smallest and largest numbers in the list.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
smallest_number = min(numbers)
largest_number = max(numbers)
print(f"The smallest number is: {smallest_number}")
print(f"The largest number is: {largest_number}")
Exercise 24: Remove Duplicates from a List
Concepts:
- Lists
- Sets
- List comprehensions
Description: Write a Python program that takes a list and returns a new list without duplicates.
Solution:
input_list = input("Enter a list of elements separated by spaces: ").split()
unique_list = list(dict.fromkeys(input_list))
print(f"The list without duplicates is: {unique_list}")
Exercise 25: Sorting a List in Ascending and Descending Order
Concepts:
- Lists
- Sorting
Description: Write a Python program that takes a list of numbers as input and returns the same list sorted in ascending and descending order.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
ascending_sorted_list = sorted(numbers)
descending_sorted_list = sorted(numbers, reverse=True)
print(f"The list sorted in ascending order is: {ascending_sorted_list}")
print(f"The list sorted in descending order is: {descending_sorted_list}")
Exercise 26: Square and Cube of Numbers in a List
Concepts:
- Lists
- Loops
- List comprehensions
Description: Write a Python program that takes a list of numbers and returns a new list containing the square and cube of each number.
Solution:
numbers = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
squares_and_cubes = [(x**2, x**3) for x in numbers]
print(f"The squares and cubes of the numbers are: {squares_and_cubes}")
Exercise 27: Count the Number of Words in a Sentence
Concepts:
- Strings
- String manipulation
Description: Write a Python program that takes a sentence as input and counts the number of words in the sentence.
Solution:
input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
word_count = len(words)
print(f"The number of words in the sentence is: {word_count}")
Exercise 28: Swapping Two Variables
Concepts:
- Variables
- Tuples
Description: Write a Python program that takes two variables as input and swaps their values.
Solution:
x = input("Enter the value of x: ")
y = input("Enter the value of y: ")
print(f"Before swapping: x = {x}, y = {y}")
x, y = y, x
print(f"After swapping: x = {x}, y = {y}")
Exercise 29: Distance Between Two Points
Concepts:
- Functions
- Input/output
- Math module
Description: Write a Python program that calculates the distance between two points in a 2D space. The coordinates of the points should be provided by the user.
Solution:
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
x1, y1 = map(float, input("Enter the coordinates of the first point (x1, y1): ").split())
x2, y2 = map(float, input("Enter the coordinates of the second point (x2, y2): ").split())
result = distance(x1, y1, x2, y2)
print(f"The distance between the two points is: {result:.2f}")
Exercise 30: Convert Temperature from Celsius to Fahrenheit and Vice Versa
Concepts:
- Functions
- Input/output
- Conditional statements
Description: Write a Python program that converts temperatures between Celsius and Fahrenheit. The user should provide the temperature value and the unit.
Solution:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
temperature = float(input("Enter the temperature value: "))
unit = input("Enter the unit (C for Celsius, F for Fahrenheit): ")
if unit.upper() == "C":
result = celsius_to_fahrenheit(temperature)
print(f"{temperature} Celsius is equal to {result:.2f} Fahrenheit")
elif unit.upper() == "F":
result = fahrenheit_to_celsius(temperature)
print(f"{temperature} Fahrenheit is equal to {result:.2f} Celsius")
else:
print("Invalid unit. Please enter 'C' for Celsius or 'F' for Fahrenheit.")
Beginner Level Exercises
Exercise 1: Calculate the Area of a Circle
Concepts:
- Basic arithmetic
- Input/output
- Variables
Description: Write a Python program that takes the radius of a circle as input from the user and calculates its area.
Solution:
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * (radius ** 2)
print(f"The area of the circle with radius {radius} is {area:.2f}")
Exercise 2: Word Frequency Counter
Concepts:
- Strings
- Dictionaries
- Loops
Description: Write a Python program that takes a string as input and counts the frequency of each word in the string.
Solution:
input_string = input("Enter a sentence: ")
words = input_string.lower().split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Word frequencies:", word_count)
Exercise 3: Simple Temperature Converter
Concepts:
- Functions
- Conditional statements
- User input
Description: Write a Python program that converts temperatures between Celsius and Fahrenheit. The program should ask the user for the temperature unit and the value to be converted.
Solution:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
unit = input("Enter the temperature unit (C for Celsius, F for Fahrenheit): ")
value = float(input("Enter the temperature value to be converted: "))
if unit.upper() == "C":
print(f"{value} Celsius is {celsius_to_fahrenheit(value):.2f} Fahrenheit.")
elif unit.upper() == "F":
print(f"{value} Fahrenheit is {fahrenheit_to_celsius(value):.2f} Celsius.")
else:
print("Invalid temperature unit.")
Exercise 4: Odd or Even Number Checker
Concepts:
- Modular arithmetic
- Conditional statements
Description: Write a Python program that checks whether a given number is odd or even.
Solution:
number = int(input("Enter an integer: "))
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
Exercise 5: Simple File Operations
Concepts:
- File I/O
- Exception handling
- String manipulation
Description: Write a Python program that reads a text file, converts its content to uppercase, and writes the result to a new file. If the input file does not exist, display an error message.
Solution:
input_file = input("Enter the name of the input file: ")
output_file = input("Enter the name of the output file: ")
try:
with open(input_file, "r") as infile:
content = infile.read()
uppercase_content = content.upper()
with open(output_file, "w") as outfile:
outfile.write(uppercase_content)
print("The content has been converted to uppercase and saved in the output file.")
except FileNotFoundError:
print(f"The file '{input_file}' does not exist.")
Exercise 6: List of Multiples
Concepts:
- Loops
- Lists
- Arithmetic
Description: Write a Python program that takes a number as input and returns a list of its first 10 multiples.
Solution:
number = int(input("Enter a number: "))
multiples = [number * i for i in range(1, 11)]
print(f"The first 10 multiples of {number} are: {multiples}")
Exercise 7: Palindrome Checker
Concepts:
- Strings
- Conditional statements
- String manipulation
Description: Write a Python program that checks whether a given word or phrase is a palindrome. Ignore spaces, punctuation, and capitalization.
Solution:
import re
input_string = input("Enter a word or phrase: ")
processed_string = re.sub(r'\W+', '', input_string.lower())
reversed_string = processed_string[::-1]
if processed_string == reversed_string:
print(f"'{input_string}' is a palindrome.")
else:
print(f"'{input_string}' is not a palindrome.")
Exercise 8: Simple Interest Calculator
Concepts:
- Arithmetic
- Input/output
- Variables
Description: Write a Python program that calculates the simple interest for a given principal amount, rate of interest, and number of years.
Solution:
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest (percentage): "))
years = int(input("Enter the number of years: "))
interest = principal * rate * years / 100
total_amount = principal + interest
print(f"The simple interest is: {interest:.2f}")
print(f"The total amount after {years} years is: {total_amount:.2f}")
Exercise 9: Fibonacci Sequence Generator
Concepts:
- Loops
- Lists
- Functions
Description: Write a Python program that generates the first n numbers of the Fibonacci sequence, where n is provided by the user.
Solution:
def generate_fibonacci(n):
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
n = int(input("Enter the number of Fibonacci numbers to generate: "))
fibonacci_sequence = generate_fibonacci(n)
print(f"The first {n} Fibonacci numbers are: {fibonacci_sequence}")
Exercise 10: Leap Year Checker
Concepts:
- Conditional statements
- Modular arithmetic
Description: Write a Python program that checks whether a given year is a leap year.
Solution:
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Exercise 11: Prime Number Checker
Concepts:
- Loops
- Conditional statements
- Functions
Description: Write a Python program that checks whether a given number is a prime number.
Solution:
def is_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Exercise 12: Count Vowels in a String
Concepts:
- Strings
- Loops
- Dictionaries
Description: Write a Python program that counts the number of vowels in a given string.
Solution:
input_string = input("Enter a string: ").lower()
vowels = "aeiou"
vowel_count = {}
for char in input_string:
if char in vowels:
if char in vowel_count:
vowel_count[char] += 1
else:
vowel_count[char] = 1
print("Vowel count:", vowel_count)
Exercise 13: Calculate the Factorial of a Number
Concepts:
- Loops
- Conditional statements
- Functions
Description: Write a Python program that calculates the factorial of a given number using loops.
Solution:
def factorial(number):
if number == 0 or number == 1:
return 1
result = 1
for i in range(2, number + 1):
result *= i
return result
number = int(input("Enter a number: "))
print(f"The factorial of {number} is {factorial(number)}")
Exercise 14: Sum of Digits in a Number
Concepts:
- Loops
- Arithmetic
- Strings
Description: Write a Python program that calculates the sum of the digits of a given integer.
Solution:
number = int(input("Enter an integer: "))
sum_of_digits = sum(int(digit) for digit in str(number))
print(f"The sum of the digits of {number} is {sum_of_digits}")
Exercise 15: Caesar Cipher Encoder
Concepts:
- Strings
- Loops
- Modular arithmetic
Description: Write a Python program that implements a simple Caesar cipher. The program should take a string and an integer shift value as input, and return the encoded string.
Solution:
def caesar_cipher(text, shift):
encrypted = []
for char in text:
if char.isalpha():
shift_amount = shift % 26
new_ord = ord(char) + shift_amount
if char.islower():
if new_ord > ord("z"):
new_ord -= 26
else:
if new_ord > ord("Z"):
new_ord -= 26
encrypted.append(chr(new_ord))
else:
encrypted.append(char)
return "".join(encrypted)
text = input("Enter a string: ")
shift = int(input("Enter the shift value: "))
encoded_text = caesar_cipher(text, shift)
print(f"The encoded text is: {encoded_text}")
Exercise 16: Reverse a String
Concepts:
- Strings
- Loops
- Slicing
Description: Write a Python program that reverses a given string.
Solution:
input_string = input("Enter a string: ")
reversed_string = input_string[::-1]
print(f"The reversed string is: {reversed_string}")
Exercise 17: Count Occurrences of a Character
Concepts:
- Strings
- Loops
- Dictionaries
Description: Write a Python program that counts the occurrences of a specific character in a given string.
Solution:
input_string = input("Enter a string: ")
target_char = input("Enter a character to count: ")
count = input_string.lower().count(target_char.lower())
print(f"The character '{target_char}' occurs {count} times in the string.")
Exercise 18: Print the ASCII Value of a Character
Concepts:
- Input/output
- ord() function
Description: Write a Python program that takes a single character as input and prints its ASCII value.
Solution:
char = input("Enter a single character: ")
if len(char) == 1:
print(f"The ASCII value of '{char}' is {ord(char)}")
else:
print("Invalid input. Please enter a single character.")
Exercise 19: Simple Calculator
Concepts:
- Functions
- Input/output
- Conditional statements
Description: Write a Python program that creates a simple calculator that can perform addition, subtraction, multiplication, and division. The program should ask the user for the operation, the two numbers, and then display the result.
Solution:
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):
return x / y
operation = input("Enter the operation (add, subtract, multiply, divide): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operation.lower() == "add":
print(f"The result is: {add(num1, num2)}")
elif operation.lower() == "subtract":
print(f"The result is: {subtract(num1, num2)}")
elif operation.lower() == "multiply":
print(f"The result is: {multiply(num1, num2)}")
elif operation.lower() == "divide":
if num2 == 0:
print("Error: Division by zero is not allowed.")
else:
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid operation.")
Exercise 20: Longest Word in a Sentence
Concepts:
- Strings
- Loops
- String manipulation
Description: Write a Python program that takes a sentence as input and returns the longest word in the sentence.
Solution:
input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
longest_word = ""
max_length = 0
for word in words:
if len(word) > max_length:
max_length = len(word)
longest_word = word
print(f"The longest word in the sentence is: {longest_word}")
Exercise 21: Calculate the Average of Numbers in a List
Concepts:
- Lists
- Loops
- Arithmetic
Description: Write a Python program that calculates the average of a list of numbers.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
average = sum(numbers) / len(numbers)
print(f"The average of the numbers is: {average:.2f}")
Exercise 22: Common Elements in Two Lists
Concepts:
- Lists
- Loops
- Sets
Description: Write a Python program that takes two lists and returns a list of common elements.
Solution:
list1 = input("Enter the first list of numbers separated by spaces: ").split()
list2 = input("Enter the second list of numbers separated by spaces: ").split()
common_elements = list(set(list1) & set(list2))
print(f"The common elements in the two lists are: {common_elements}")
Exercise 23: Find the Smallest and Largest Numbers in a List
Concepts:
- Lists
- Loops
- min() and max() functions
Description: Write a Python program that takes a list of numbers as input and returns the smallest and largest numbers in the list.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
smallest_number = min(numbers)
largest_number = max(numbers)
print(f"The smallest number is: {smallest_number}")
print(f"The largest number is: {largest_number}")
Exercise 24: Remove Duplicates from a List
Concepts:
- Lists
- Sets
- List comprehensions
Description: Write a Python program that takes a list and returns a new list without duplicates.
Solution:
input_list = input("Enter a list of elements separated by spaces: ").split()
unique_list = list(dict.fromkeys(input_list))
print(f"The list without duplicates is: {unique_list}")
Exercise 25: Sorting a List in Ascending and Descending Order
Concepts:
- Lists
- Sorting
Description: Write a Python program that takes a list of numbers as input and returns the same list sorted in ascending and descending order.
Solution:
numbers = [float(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
ascending_sorted_list = sorted(numbers)
descending_sorted_list = sorted(numbers, reverse=True)
print(f"The list sorted in ascending order is: {ascending_sorted_list}")
print(f"The list sorted in descending order is: {descending_sorted_list}")
Exercise 26: Square and Cube of Numbers in a List
Concepts:
- Lists
- Loops
- List comprehensions
Description: Write a Python program that takes a list of numbers and returns a new list containing the square and cube of each number.
Solution:
numbers = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
squares_and_cubes = [(x**2, x**3) for x in numbers]
print(f"The squares and cubes of the numbers are: {squares_and_cubes}")
Exercise 27: Count the Number of Words in a Sentence
Concepts:
- Strings
- String manipulation
Description: Write a Python program that takes a sentence as input and counts the number of words in the sentence.
Solution:
input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
word_count = len(words)
print(f"The number of words in the sentence is: {word_count}")
Exercise 28: Swapping Two Variables
Concepts:
- Variables
- Tuples
Description: Write a Python program that takes two variables as input and swaps their values.
Solution:
x = input("Enter the value of x: ")
y = input("Enter the value of y: ")
print(f"Before swapping: x = {x}, y = {y}")
x, y = y, x
print(f"After swapping: x = {x}, y = {y}")
Exercise 29: Distance Between Two Points
Concepts:
- Functions
- Input/output
- Math module
Description: Write a Python program that calculates the distance between two points in a 2D space. The coordinates of the points should be provided by the user.
Solution:
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
x1, y1 = map(float, input("Enter the coordinates of the first point (x1, y1): ").split())
x2, y2 = map(float, input("Enter the coordinates of the second point (x2, y2): ").split())
result = distance(x1, y1, x2, y2)
print(f"The distance between the two points is: {result:.2f}")
Exercise 30: Convert Temperature from Celsius to Fahrenheit and Vice Versa
Concepts:
- Functions
- Input/output
- Conditional statements
Description: Write a Python program that converts temperatures between Celsius and Fahrenheit. The user should provide the temperature value and the unit.
Solution:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
temperature = float(input("Enter the temperature value: "))
unit = input("Enter the unit (C for Celsius, F for Fahrenheit): ")
if unit.upper() == "C":
result = celsius_to_fahrenheit(temperature)
print(f"{temperature} Celsius is equal to {result:.2f} Fahrenheit")
elif unit.upper() == "F":
result = fahrenheit_to_celsius(temperature)
print(f"{temperature} Fahrenheit is equal to {result:.2f} Celsius")
else:
print("Invalid unit. Please enter 'C' for Celsius or 'F' for Fahrenheit.")