Practice Python Exercises
Practice Python Exercises
Exercise 1: Hello, World!
Write a Python program that prints “Hello, World!” to the console.
# Exercise 1: Hello, World!
# Print "Hello, World!"
print("Hello, World!")
Exercise 2: Sum of Two Numbers
Write a Python program that calculates and prints the sum of two numbers.
# Exercise 2: Sum of Two Numbers
# Define two numbers
num1 = 5
num2 = 3
# Calculate the sum
sum = num1 + num2
# Print the sum
print("The sum of", num1, "and", num2, "is:", sum)
Exercise 3: Area of a Rectangle
Write a Python program that calculates and prints the area of a rectangle given its length and width.
# Exercise 3: Area of a Rectangle
# Define the length and width of the rectangle
length = 6
width = 4
# Calculate the area
area = length * width
# Print the area
print("The area of the rectangle is:", area)
Exercise 4: Celsius to Fahrenheit Conversion
Write a Python program that converts a temperature in Celsius to Fahrenheit.
# Exercise 4: Celsius to Fahrenheit Conversion
# Input temperature in Celsius
celsius = 20
# Convert Celsius to Fahrenheit
fahrenheit = (celsius * 9/5) + 32
# Print the result
print("Temperature in Fahrenheit:", fahrenheit)
Exercise 5: Maximum of Three Numbers
Write a Python program that finds and prints the maximum of three numbers.
# Exercise 5: Maximum of Three Numbers
# Define three numbers
num1 = 10
num2 = 20
num3 = 15
# Find the maximum
max_num = max(num1, num2, num3)
# Print the maximum
print("The maximum of the three numbers is:", max_num)
Exercise 6: Factorial Calculation
Write a Python program that calculates and prints the factorial of a given number.
# Exercise 6: Factorial Calculation
# Function to calculate factorial
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Input number
num = 5
# Calculate factorial
result = factorial(num)
# Print the result
print("Factorial of", num, "is:", result)
Exercise 7: Simple Interest Calculation
Write a Python program that calculates and prints the simple interest given the principal amount, rate, and time.
# Exercise 7: Simple Interest Calculation
# Input principal amount, rate, and time
principal = 1000
rate = 0.05
time = 2
# Calculate simple interest
simple_interest = principal * rate * time
# Print the result
print("Simple interest:", simple_interest)
Exercise 8: Reverse a String
Write a Python program that reverses a given string.
# Exercise 8: Reverse a String
# Input string
string = "hello"
# Reverse the string
reversed_string = string[::-1]
# Print the reversed string
print("Reversed string:", reversed_string)
Exercise 9: Check for Palindrome
Write a Python program that checks if a given string is a palindrome.
# Exercise 9: Check for Palindrome
# Input string
string = "radar"
# Check if the string is a palindrome
if string == string[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Exercise 10: Count Vowels in a String
Write a Python program that counts and prints the number of vowels in a given string.
# Exercise 10: Count Vowels in a String
# Input string
string = "hello world"
# Count vowels
vowels = "aeiou"
count = sum(1 for char in string if char.lower() in vowels)
# Print the count
print("Number of vowels:", count)
Exercise 11: Check Leap Year
Write a Python program that checks if a given year is a leap year.
# Exercise 11: Check Leap Year
# Input year
year = 2024
# Check if the year is a leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
Exercise 12: Fibonacci Series
Write a Python program to generate the Fibonacci series up to a specified number of terms.
# Exercise 12: Fibonacci Series
# Function to generate Fibonacci series
def fibonacci(n):
fib_series = [0, 1]
for i in range(2, n):
next_term = fib_series[-1] + fib_series[-2]
fib_series.append(next_term)
return fib_series
# Input number of terms
terms = 10
# Generate Fibonacci series
series = fibonacci(terms)
# Print the series
print("Fibonacci Series:", series)
Exercise 13: Prime Number Check
Write a Python program that checks if a given number is a prime number.
# Exercise 13: Prime Number Check
# Input number
num = 17
# Check if the number is prime
is_prime = True
if num <= 1:
is_prime = False
else:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
# Print the result
if is_prime:
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
Exercise 14: Count Words in a String
Write a Python program that counts and prints the number of words in a given string.
# Exercise 14: Count Words in a String
# Input string
string = "Hello, how are you?"
# Count words
word_count = len(string.split())
# Print the count
print("Number of words:", word_count)
Exercise 15: Sum of Digits
Write a Python program that calculates and prints the sum of digits of a given number.
# Exercise 15: Sum of Digits
# Input number
num = 12345
# Calculate sum of digits
digit_sum = sum(int(digit) for digit in str(num))
# Print the sum
print("Sum of digits:", digit_sum)
Exercise 16: Calculate BMI
Write a Python program that calculates the Body Mass Index (BMI) given the height (in meters) and weight (in kilograms) of a person.
# Exercise 16: Calculate BMI
# Input height and weight
height = 1.75
weight = 70
# Calculate BMI
bmi = weight / (height ** 2)
# Print the BMI
print("BMI:", bmi)
Exercise 17: Count Even and Odd Numbers
Write a Python program that counts and prints the number of even and odd numbers in a given list of integers.
# Exercise 17: Count Even and Odd Numbers
# Input list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Count even and odd numbers
even_count = sum(1 for num in numbers if num % 2 == 0)
odd_count = len(numbers) - even_count
# Print the counts
print("Number of even numbers:", even_count)
print("Number of odd numbers:", odd_count)
Exercise 18: Remove Duplicates from a List
Write a Python program that removes duplicates from a given list and prints the updated list.
# Exercise 18: Remove Duplicates from a List
# Input list with duplicates
numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6]
# Remove duplicates
unique_numbers = list(set(numbers))
# Print the updated list
print("List with duplicates removed:", unique_numbers)
Exercise 19: Check Anagram
Write a Python program that checks if two given strings are anagrams.
# Exercise 19: Check Anagram
# Input strings
str1 = "listen"
str2 = "silent"
# Check if the strings are anagrams
is_anagram = sorted(str1) == sorted(str2)
# Print the result
if is_anagram:
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
Exercise 20: Find Largest Element in a List
Write a Python program that finds and prints the largest element in a given list of numbers.
# Exercise 20: Find Largest Element in a List
# Input list of numbers
numbers = [10, 5, 20, 15, 30]
# Find the largest element
max_num = max(numbers)
# Print the largest element
print("Largest element:", max_num)
Exercise 21: Check Armstrong Number
Write a Python program that checks if a given number is an Armstrong number.
# Exercise 21: Check Armstrong Number
# Input number
num = 153
# Calculate the sum of cubes of digits
temp = num
sum = 0
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# Check if the number is an Armstrong number
is_armstrong = num == sum
# Print the result
if is_armstrong:
print(num, "is an Armstrong number.")
else:
print(num, "is not an Armstrong number.")
Exercise 22: Check Palindrome Number
Write a Python program that checks if a given number is a palindrome number.
# Exercise 22: Check Palindrome Number
# Input number
num = 12321
# Convert the number to a string
num_str = str(num)
# Check if the number is a palindrome
is_palindrome = num_str == num_str[::-1]
# Print the result
if is_palindrome:
print(num, "is a palindrome number.")
else:
print(num, "is not a palindrome number.")
Exercise 23: Sort Words in Alphabetical Order
Write a Python program that takes a list of words and sorts them in alphabetical order.
# Exercise 23: Sort Words in Alphabetical Order
# Input list of words
words = ["apple", "banana", "orange", "grape", "pineapple"]
# Sort the words
sorted_words = sorted(words)
# Print the sorted words
print("Words in alphabetical order:", sorted_words)
Exercise 24: Merge Two Lists
Write a Python program that merges two given lists into a single list and removes duplicates.
# Exercise 24: Merge Two Lists
# Input lists
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Merge and remove duplicates
merged_list = list(set(list1 + list2))
# Print the merged list
print("Merged list without duplicates:", merged_list)
Exercise 25: Count Frequency of Characters in a String
Write a Python program that counts the frequency of each character in a given string.
# Exercise 25: Count Frequency of Characters in a String
# Input string
string = "hello"
# Count frequency of characters
char_frequency = {}
for char in string:
char_frequency[char] = char_frequency.get(char, 0) + 1
# Print the frequency of characters
for char, freq in char_frequency.items():
print(char, ":", freq)Exercise 26: Find Second Largest Element in a List
Write a Python program that finds and prints the second largest element in a given list of numbers.
# Exercise 26: Find Second Largest Element in a List
# Input list of numbers
numbers = [10, 20, 30, 40, 50]
# Find the second largest element
second_largest = sorted(set(numbers))[-2]
# Print the second largest element
print("Second largest element:", second_largest)
Exercise 27: Merge Sort Algorithm
Write a Python program that implements the merge sort algorithm to sort a given list of numbers.
# Exercise 27: Merge Sort Algorithm
# Function to merge two sorted lists
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# Function to perform merge sort
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left = merge_sort(nums[:mid])
right = merge_sort(nums[mid:])
return merge(left, right)
# Input list of numbers
numbers = [5, 3, 8, 1, 9, 2, 7, 6, 4]
# Sort the list using merge sort
sorted_numbers = merge_sort(numbers)
# Print the sorted list
print("Sorted list:", sorted_numbers)
Exercise 28: Reverse Words in a String
Write a Python program that reverses the order of words in a given string.
# Exercise 28: Reverse Words in a String
# Input string
string = "Hello World"
# Reverse the order of words
reversed_string = " ".join(string.split()[::-1])
# Print the reversed string
print(“Reversed string:”, reversed_string)
Exercise 29: Find Missing Number
Write a Python program that finds and prints the missing number in a given list of consecutive numbers from 1 to N.
# Exercise 29: Find Missing Number
# Input list of numbers
numbers = [1, 2, 3, 4, 6, 7, 8, 9, 10]
# Find the missing number
n = len(numbers) + 1
missing_number = (n * (n + 1) // 2) - sum(numbers)
# Print the missing number
print("Missing number:", missing_number)Exercise 30: Remove Punctuation from a String
Write a Python program that removes punctuation characters from a given string.
# Exercise 30: Remove Punctuation from a String
# Import string module for accessing punctuation characters
import string
# Input string
string_with_punctuation = "Hello, World! This is a sample string."
# Remove punctuation
clean_string = string_with_punctuation.translate(str.maketrans("", "", string.punctuation))
# Print the cleaned string
print("Cleaned string:", clean_string)
Exercise 31: Calculate Power of a Number
Write a Python program that calculates and prints the power of a given number raised to another number.
# Exercise 31: Calculate Power of a Number
# Input base and exponent
base = 2
exponent = 5
# Calculate power
power = base ** exponent
# Print the result
print(“Power of”, base, “raised to”, exponent, “is:”, power)
Exercise 32: Check Strong Number
Write a Python program that checks if a given number is a strong number.
# Exercise 32: Check Strong Number
# Function to calculate factorial of a number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Input number
num = 145
# Calculate the sum of factorials of digits
temp = num
sum = 0
while temp > 0:
digit = temp % 10
sum += factorial(digit)
temp //= 10
# Check if the number is a strong number
is_strong = num == sum
# Print the result
if is_strong:
print(num, "is a strong number.")
else:
print(num, "is not a strong number.")
Exercise 33: Find Median of Two Sorted Lists
Write a Python program that finds the median of two sorted lists.
# Exercise 33: Find Median of Two Sorted Lists
# Input sorted lists
list1 = [1, 3, 5]
list2 = [2, 4, 6]
# Merge the lists
merged_list = sorted(list1 + list2)
# Calculate median
n = len(merged_list)
if n % 2 == 0:
median = (merged_list[n//2 - 1] + merged_list[n//2]) / 2
else:
median = merged_list[n//2]
# Print the median
print("Median of the two lists:", median)
Exercise 34: Convert Decimal to Binary
Write a Python program that converts a decimal number to its binary representation.
Solution:
# Exercise 34: Convert Decimal to Binary
# Input decimal number
decimal = 10
# Convert decimal to binary
binary = bin(decimal)[2:]
# Print the binary representation
print("Binary representation of", decimal, "is:", binary)
Exercise 35: Generate Random Password
Write a Python program that generates a random password of a specified length.
# Exercise 35: Generate Random Password
# Import random module
import random
# Define characters for password generation
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*"
# Input password length
length = 10
# Generate random password
password = "".join(random.sample(characters, length))
# Print the password
print("Random password:", password)
Exercise 36: Find GCD of Two Numbers
Write a Python program that finds and prints the Greatest Common Divisor (GCD) of two given numbers.
# Exercise 36: Find GCD of Two Numbers
# Function to calculate GCD using Euclid's algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Input numbers
num1 = 24
num2 = 36
# Find and print the GCD
print("GCD of", num1, "and", num2, "is:", gcd(num1, num2))
Exercise 37: Find LCM of Two Numbers
Write a Python program that finds and prints the Least Common Multiple (LCM) of two given numbers.
# Exercise 37: Find LCM of Two Numbers
# Function to calculate LCM
def lcm(a, b):
return (a * b) // gcd(a, b)
# Input numbers
num1 = 24
num2 = 36
# Find and print the LCM
print("LCM of", num1, "and", num2, "is:", lcm(num1, num2))
Exercise 38: Generate Random Numbers
Write a Python program that generates a specified number of random numbers within a given range.
# Exercise 38: Generate Random Numbers
# Import random module
import random
# Input parameters
start = 1
end = 100
count = 5
# Generate random numbers
random_numbers = [random.randint(start, end) for _ in range(count)]
# Print the random numbers
print("Random numbers:", random_numbers)
Exercise 39: Find Square Root
Write a Python program that finds and prints the square root of a given number.
# Exercise 39: Find Square Root
# Import math module
import math
# Input number
num = 25
# Find and print the square root
print("Square root of", num, "is:", math.sqrt(num))
Exercise 40: Calculate Compound Interest
Write a Python program that calculates and prints the compound interest given the principal amount, rate, and time.
# Exercise 40: Calculate Compound Interest
# Input principal amount, rate, and time
principal = 1000
rate = 0.05
time = 2
# Calculate compound interest
compound_interest = principal * ((1 + rate) ** time - 1)
# Print the compound interest
print("Compound interest:", compound_interest)
Exercise 42: Find Factorial of a Number
Write a Python program that finds and prints the factorial of a given number.
# Exercise 42: Find Factorial of a Number
# Input number
num = 5
# Function to calculate factorial
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Calculate factorial
fact = factorial(num)
# Print the factorial
print("Factorial of", num, "is:", fact)
Exercise 43: Check Disarium Number
Write a Python program that checks if a given number is a Disarium number.
# Exercise 43: Check Disarium Number
# Input number
num = 89
# Function to calculate the sum of digits raised to their respective positions
def calculate_disarium_sum(n):
digit_count = len(str(n))
temp = n
sum = 0
while temp > 0:
digit = temp % 10
sum += digit ** digit_count
temp //= 10
digit_count -= 1
return sum
# Check if the number is a Disarium number
is_disarium = num == calculate_disarium_sum(num)
# Print the result
if is_disarium:
print(num, "is a Disarium number.")
else:
print(num, "is not a Disarium number.")
Exercise 44: Calculate Natural Logarithm
Write a Python program that calculates and prints the natural logarithm of a given number.
# Exercise 44: Calculate Natural Logarithm
# Import math module
import math
# Input number
num = 2.71828
# Calculate natural logarithm
log_value = math.log(num)
# Print the natural logarithm
print("Natural logarithm of", num, "is:", log_value)
Exercise 45: Generate Pascal’s Triangle
Write a Python program that generates and prints Pascal’s triangle up to a specified number of rows.
# Exercise 45: Generate Pascal's Triangle
# Function to generate Pascal's triangle
def generate_pascals_triangle(rows):
triangle = []
for i in range(rows):
row = [1]
if triangle:
last_row = triangle[-1]
row.extend([sum(pair) for pair in zip(last_row, last_row[1:])])
row.append(1)
triangle.append(row)
return triangle
# Input number of rows
num_rows = 5
# Generate Pascal's triangle
pascals_triangle = generate_pascals_triangle(num_rows)
# Print the triangle
print("Pascal's Triangle:")
for row in pascals_triangle:
print(row)
Exercise 46: Count Vowels and Consonants
Write a Python program that counts and prints the number of vowels and consonants in a given string.
# Exercise 46: Count Vowels and Consonants
# Input string
string = "Hello World"
# Function to count vowels and consonants
def count_vowels_and_consonants(s):
vowels = 0
consonants = 0
for char in s:
if char.lower() in 'aeiou':
vowels += 1
elif char.isalpha():
consonants += 1
return vowels, consonants
# Count vowels and consonants
vowel_count, consonant_count = count_vowels_and_consonants(string)
# Print the counts
print("Number of vowels:", vowel_count)
print("Number of consonants:", consonant_count)
Exercise 47: Check Harshad Number
Write a Python program that checks if a given number is a Harshad number.
# Exercise 47: Check Harshad Number
# Input number
num = 18
# Function to calculate sum of digits
def sum_of_digits(n):
return sum(int(digit) for digit in str(n))
# Check if the number is a Harshad number
is_harshad = num % sum_of_digits(num) == 0
# Print the result
if is_harshad:
print(num, "is a Harshad number.")
else:
print(num, "is not a Harshad number.")
Exercise 48: Check Duck Number
Write a Python program that checks if a given number is a Duck number.
# Exercise 48: Check Duck Number
# Input number
num = 503
# Check if the number is a Duck number
is_duck = '0' in str(num)[1:]
# Print the result
if is_duck:
print(num, "is a Duck number.")
else:
print(num, "is not a Duck number.")
Exercise 49: Convert Octal to Decimal
Write a Python program that converts an octal number to its decimal representation.
# Exercise 49: Convert Octal to Decimal
# Input octal number
octal = '52'
# Convert octal to decimal
decimal = int(octal, 8)
# Print the decimal representation
print("Decimal representation of", octal, "is:", decimal)
Exercise 50: Find Fibonacci Series
Write a Python program that generates and prints the Fibonacci series up to a specified number of terms.
# Exercise 50: Find Fibonacci Series
# Input number of terms
terms = 10
# Initialize first two terms
a, b = 0, 1
# Print Fibonacci series
print("Fibonacci Series:")
for _ in range(terms):
print(a, end=" ")
a,
Exercise 51: Check Perfect Number
Write a Python program that checks if a given number is a perfect number.
# Exercise 51: Check Perfect Number
# Input number
num = 28
# Function to check if a number is perfect
def is_perfect(num):
divisors_sum = sum(i for i in range(1, num) if num % i == 0)
return divisors_sum == num
# Check if the number is perfect
is_perfect_number = is_perfect(num)
# Print the result
if is_perfect_number:
print(num, "is a perfect number.")
else:
print(num, "is not a perfect number.")
Exercise 52: Find Sum of Squares of First N Natural Numbers
Write a Python program that finds and prints the sum of squares of the first N natural numbers.
# Exercise 52: Find Sum of Squares of First N Natural Numbers
# Input number of terms
n = 5
# Calculate sum of squares
sum_of_squares = sum(i**2 for i in range(1, n+1))
# Print the result
print("Sum of squares of first", n, "natural numbers:", sum_of_squares)
Exercise 53: Calculate Harmonic Mean
Write a Python program that calculates and prints the harmonic mean of a given list of numbers.
# Exercise 53: Calculate Harmonic Mean
# Input list of numbers
numbers = [4, 9, 25]
# Calculate harmonic mean
harmonic_mean = len(numbers) / sum(1 / num for num in numbers)
# Print the harmonic mean
print("Harmonic mean of", numbers, "is:", harmonic_mean)
Exercise 54: Reverse a Number
Write a Python program that reverses a given number and prints the reversed number.
# Exercise 54: Reverse a Number
# Input number
num = 12345
# Reverse the number
reversed_num = int(str(num)[::-1])
# Print the reversed number
print("Reversed number:", reversed_num)
Exercise 55: Check Strong Prime Number
Write a Python program that checks if a given number is a strong prime number.
# Exercise 55: Check Strong Prime Number
# Function to check if a number is prime
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# Function to check if a number is strong
def is_strong(num):
return is_prime(num) and is_prime(sum(int(digit) for digit in str(num)))
# Input number
num = 17
# Check if the number is a strong prime
is_strong_prime = is_strong(num)
# Print the result
if is_strong_prime:
print(num, "is a strong prime number.")
else:
print(num, "is not a strong prime number.")
Exercise 56: Find ASCII Value of a Character
Write a Python program that takes a character as input and prints its corresponding ASCII value.
# Exercise 56: Find ASCII Value of a Character
# Input character
char = 'A'
# Get ASCII value
ascii_value = ord(char)
# Print the ASCII value
print("ASCII value of", char, "is:", ascii_value)
Exercise 57: Check Happy Number
Write a Python program that checks if a given number is a happy number.
# Exercise 57: Check Happy Number
# Function to calculate the sum of squares of digits
def square_digits_sum(n):
return sum(int(digit)**2 for digit in str(n))
# Function to check if a number is happy
def is_happy(num):
seen = set()
while num != 1 and num not in seen:
seen.add(num)
num = square_digits_sum(num)
return num == 1
# Input number
num = 19
# Check if the number is happy
is_happy_number = is_happy(num)
# Print the result
if is_happy_number:
print(num, "is a happy number.")
else:
print(num, "is not a happy number.")Exercise 58: Find Prime Factors of a Number
Write a Python program that finds and prints the prime factors of a given number.
# Exercise 58: Find Prime Factors of a Number
# Function to find prime factors
def prime_factors(n):
factors = []
divisor = 2
while n > 1:
while n % divisor == 0:
factors.append(divisor)
n //= divisor
divisor += 1
return factors
# Input number
num = 36
# Find prime factors
factors = prime_factors(num)
# Print the prime factors
print("Prime factors of", num, "are:", factors)
Exercise 59: Check Palindrome String
Write a Python program that checks if a given string is a palindrome string.
# Exercise 59: Check Palindrome String
# Input string
string = "radar"
# Check if the string is a palindrome
is_palindrome = string == string[::-1]
# Print the result
if is_palindrome:
print(string, "is a palindrome string.")
else:
print(string, "is not a palindrome string.")
Exercise 60: Check Automorphic Number
Write a Python program that checks if a given number is an Automorphic number.
# Exercise 60: Check Automorphic Number
# Function to check if a number is automorphic
def is_automorphic(num):
square = num ** 2
return str(square).endswith(str(num))
# Input number
num = 25
# Check if the number is automorphic
is_automorphic_number = is_automorphic(num)
# Print the result
if is_automorphic_number:
print(num, "is an automorphic number.")
else:
Exercise 61: Find HCF (GCD) of Two Numbers
Write a Python program that calculates and prints the Highest Common Factor (HCF) or Greatest Common Divisor (GCD) of two given numbers.
# Exercise 61: Find HCF (GCD) of Two Numbers
# Function to calculate GCD using Euclidean algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Input numbers
num1 = 48
num2 = 60
# Find and print the GCD
print("GCD of", num1, "and", num2, "is:", gcd(num1, num2))
Exercise 62: Generate Random Dates within a Range
Write a Python program that generates and prints a specified number of random dates within a given range.
# Exercise 62: Generate Random Dates within a Range
# Import necessary modules
import random
from datetime import datetime, timedelta
# Input number of random dates and date range
num_dates = 5
start_date = datetime(2022, 1, 1)
end_date = datetime(2022, 12, 31)
# Generate and print random dates
print("Random Dates:")
for _ in range(num_dates):
random_date = start_date + timedelta(days=random.randint(0, (end_date - start_date).days))
print(random_date.strftime("%Y-%m-%d"))
Exercise 63: Check Smooth Number
Write a Python program that checks if a given number is a smooth number.
# Exercise 63: Check Smooth Number
# Function to check if a number is smooth
def is_smooth(num):
if num < 2:
return False
for divisor in [2, 3, 5]:
while num % divisor == 0:
num //= divisor
return num == 1
# Input number
num = 60
# Check if the number is smooth
is_smooth_number = is_smooth(num)
# Print the result
if is_smooth_number:
print(num, "is a smooth number.")
else:
print(num, "is not a smooth number.")
Exercise 64: Find Perimeter of a Rectangle
Write a Python program that calculates and prints the perimeter of a rectangle given its length and width.
# Exercise 64: Find Perimeter of a Rectangle
# Input length and width
length = 5
width = 3
# Calculate perimeter
perimeter = 2 * (length + width)
# Print the perimeter
print("Perimeter of the rectangle:", perimeter)
Exercise 65: Find Armstrong Number
Write a Python program that checks if a given number is an Armstrong number.
# Exercise 65: Find Armstrong Number
# Function to calculate the sum of cubes of digits
def sum_of_cubes(n):
return sum(int(digit)**3 for digit in str(n))
# Function to check if a number is Armstrong
def is_armstrong(num):
return num == sum_of_cubes(num)
# Input number
num = 153
# Check if the number is Armstrong
is_armstrong_number = is_armstrong(num)
# Print the result
if is_armstrong_number:
print(num, "is an Armstrong number.")
else:
print(num, "is not an Armstrong number.")
Exercise 66: Calculate Area of a Circle
Write a Python program that calculates and prints the area of a circle given its radius.
# Exercise 66: Calculate Area of a Circle
# Import math module for pi
import math
# Input radius
radius = 4
# Calculate area
area = math.pi * radius**2
# Print the area
print("Area of the circle:", area)
Exercise 67: Check Amicable Numbers
Write a Python program that checks if two given numbers are amicable numbers.
# Exercise 67: Check Amicable Numbers
# Function to calculate the sum of proper divisors of a number
def sum_of_divisors(n):
return sum(i for i in range(1, n) if n % i == 0)
# Function to check if two numbers are amicable
def are_amicable(num1, num2):
return sum_of_divisors(num1) == num2 and sum_of_divisors(num2) == num1
# Input numbers
num1 = 220
num2 = 284
# Check if the numbers are amicable
are_amicable_numbers = are_amicable(num1, num2)
# Print the result
if are_amicable_numbers:
print(num1, "and", num2, "are amicable numbers.")
else:
print(num1, "and", num2, "are not amicable numbers.")
Exercise 68: Calculate Area of a Triangle
Write a Python program that calculates and prints the area of a triangle given its base and height.
# Exercise 68: Calculate Area of a Triangle
# Input base and height
base = 6
height = 8
# Calculate area
area = 0.5 * base * height
# Print the area
print("Area of the triangle:", area)
Exercise 69: Check Leap Year
Write a Python program that checks if a given year is a leap year.
# Exercise 69: Check Leap Year
# Function to check if a year is a leap year
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
return year % 400 == 0
else:
return True
else:
return False
# Input year
year = 2024
# Check if the year is a leap year
is_leap = is_leap_year(year)
# Print the result
if is_leap:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
Exercise 70: Generate Fibonacci Series
Write a Python program that generates and prints the Fibonacci series up to a specified number of terms.
# Exercise 70: Generate Fibonacci Series
# Input number of terms
terms = 10
# Initialize first two terms
a, b = 0, 1
# Print Fibonacci series
print("Fibonacci Series:")
for _ in range(terms):
print(a, end=" ")
a, b = b, a + b
Exercise 71: Word Frequency Counter
Write a Python program that reads a text file, counts the frequency of each word in the file, and prints the word frequencies in descending order.
Steps:
- Read the content of the text file.
- Tokenize the content into words.
- Count the frequency of each word.
- Store the word frequencies in a dictionary.
- Sort the dictionary by values (word frequencies) in descending order.
- Print the sorted word frequencies.
from collections import defaultdict
import re
def word_frequency_counter(filename):
# Step 1: Read the content of the text file
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
# Step 2: Tokenize the content into words
words = re.findall(r'\b\w+\b', content.lower())
# Step 3: Count the frequency of each word
word_freq = defaultdict(int)
for word in words:
word_freq[word] += 1
# Step 4: Sort the dictionary by values in descending order
sorted_word_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
# Step 5: Print the sorted word frequencies
for word, freq in sorted_word_freq:
print(f'{word}: {freq}')
# Example usage:
filename = 'sample.txt' # Replace with your filename
word_frequency_counter(filename)
Exercise 72: File Copy with Encryption
Write a Python program that copies the contents of one file to another while encrypting the data. You can choose a simple encryption technique, such as Caesar cipher, to encrypt the data.
Steps:
- Read the content of the source file.
- Encrypt the content using a chosen encryption technique.
- Write the encrypted content to the destination file.
# Step 1: Read the content of the source file
def read_file(filename):
with open(filename, 'r') as file:
return file.read()
# Step 2: Encrypt the content using Caesar cipher
def caesar_cipher_encrypt(text, shift):
encrypted_text = ''
for char in text:
if char.isalpha():
if char.islower():
encrypted_text += chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
else:
encrypted_text += chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
else:
encrypted_text += char
return encrypted_text
# Step 3: Write the encrypted content to the destination file
def write_encrypted_content(filename, encrypted_text):
with open(filename, 'w') as file:
file.write(encrypted_text)
# Main function to execute the program
def main():
source_filename = 'source.txt' # Update with the filename of your source file
destination_filename = 'destination.txt' # Update with the filename of your destination file
shift = 3 # Define the shift for Caesar cipher
# Read content from source file
source_content = read_file(source_filename)
# Encrypt content using Caesar cipher
encrypted_content = caesar_cipher_encrypt(source_content, shift)
# Write encrypted content to destination file
write_encrypted_content(destination_filename, encrypted_content)
print("Content encrypted and copied to destination file.")
if __name__ == "__main__":
main()
Exercise 73: File Word Reversal
Write a Python program that reads the content of a text file, reverses the order of the words in each line, and writes the modified content to another file.
Steps:
- Read the content of the source file.
- Split the content into lines.
- For each line, split the line into words.
- Reverse the order of the words in each line.
- Join the words back into lines.
- Write the modified content to the destination file.
# Exercise: File Word Reversal
# Step 1: Read the content of the source file
def read_file(filename):
with open(filename, 'r') as file:
return file.readlines()
# Step 2: Reverse the order of words in each line
def reverse_words(line):
words = line.split()
reversed_words = ' '.join(reversed(words))
return reversed_words
# Step 3: Write the modified content to the destination file
def write_modified_content(filename, modified_content):
with open(filename, 'w') as file:
file.writelines(modified_content)
# Main function to execute the program
def main():
source_filename = 'source.txt' # Update with the filename of your source file
destination_filename = 'destination.txt' # Update with the filename of your destination file
# Read content from source file
lines = read_file(source_filename)
# Reverse the order of words in each line
reversed_lines = [reverse_words(line) for line in lines]
# Write modified content to destination file
write_modified_content(destination_filename, reversed_lines)
print("Content reversed and written to destination file.")
if __name__ == "__main__":
main()
Exercise 74: File Line Reversal
Write a Python program that reads the content of a text file, reverses the order of lines, and writes the modified content to another file.
Steps:
- Read the content of the source file.
- Split the content into lines.
- Reverse the order of lines.
- Write the modified content to the destination file.
# Exercise: File Line Reversal
# Step 1: Read the content of the source file
def read_file(filename):
with open(filename, 'r') as file:
return file.readlines()
# Step 2: Reverse the order of lines
def reverse_lines(lines):
return reversed(lines)
# Step 3: Write the modified content to the destination file
def write_modified_content(filename, modified_content):
with open(filename, 'w') as file:
file.writelines(modified_content)
# Main function to execute the program
def main():
source_filename = 'source.txt' # Update with the filename of your source file
destination_filename = 'destination.txt' # Update with the filename of your destination file
# Read content from source file
lines = read_file(source_filename)
# Reverse the order of lines
reversed_lines = reverse_lines(lines)
# Write modified content to destination file
write_modified_content(destination_filename, reversed_lines)
print("Content reversed and written to destination file.")
if __name__ == "__main__":
main()
Exercise 75: File Concatenation
Write a Python program that reads the content of multiple text files, concatenates their content, and writes the combined content to another file.
Steps:
- Read the content of each source file.
- Concatenate the content of all files.
- Write the combined content to the destination file.
# Exercise: File Concatenation
# Step 1: Read the content of each source file
def read_files(filenames):
combined_content = []
for filename in filenames:
with open(filename, 'r') as file:
combined_content.extend(file.readlines())
return combined_content
# Step 2: Write the combined content to the destination file
def write_combined_content(destination_filename, combined_content):
with open(destination_filename, 'w') as file:
file.writelines(combined_content)
# Main function to execute the program
def main():
source_filenames = ['file1.txt', 'file2.txt', 'file3.txt'] # Update with the filenames of your source files
destination_filename = 'combined.txt' # Update with the filename of your destination file
# Read content from source files
combined_content = read_files(source_filenames)
# Write combined content to destination file
write_combined_content(destination_filename, combined_content)
print("Content concatenated and written to destination file.")
if __name__ == "__main__":
main()
Exercise 76: File Word Count
Write a Python program that reads the content of a text file, counts the occurrences of each word, and prints the word counts.
Steps:
- Read the content of the source file.
- Tokenize the content into words.
- Count the occurrences of each word.
- Print the word counts.
# Exercise: File Word Count
# Step 1: Read the content of the source file
def read_file(filename):
with open(filename, 'r') as file:
return file.read()
# Step 2: Tokenize the content into words
def tokenize(text):
return text.split()
# Step 3: Count the occurrences of each word
def count_word_frequency(words):
word_frequency = {}
for word in words:
word_frequency[word] = word_frequency.get(word, 0) + 1
return word_frequency
# Step 4: Print the word counts
def print_word_count(word_frequency):
for word, count in word_frequency.items():
print(f'{word}: {count}')
# Main function to execute the program
def main():
filename = 'sample.txt' # Update with the filename of your source file
# Read content from source file
text = read_file(filename)
# Tokenize content into words
words = tokenize(text)
# Count word frequency
word_frequency = count_word_frequency(words)
# Print word counts
print_word_count(word_frequency)
if __name__ == "__main__":
main()
Exercise 77: File Line Count
Write a Python program that reads the content of a text file, counts the number of lines, and prints the total line count.
Steps:
- Read the content of the source file.
- Split the content into lines.
- Count the number of lines.
- Print the total line count.
# Exercise: File Line Count
# Step 1: Read the content of the source file
def read_file(filename):
with open(filename, 'r') as file:
return file.readlines()
# Step 2: Count the number of lines
def count_lines(lines):
return len(lines)
# Step 3: Print the total line count
def print_line_count(total_lines):
print(f'Total number of lines: {total_lines}')
# Main function to execute the program
def main():
filename = 'sample.txt' # Update with the filename of your source file
# Read content from source file
lines = read_file(filename)
# Count the number of lines
total_lines = count_lines(lines)
# Print the total line count
print_line_count(total_lines)
if __name__ == "__main__":
main()Exercise 78: File Word Replacement
Write a Python program that reads the content of a text file, replaces a specific word with another word, and writes the modified content to another file.
Steps:
- Read the content of the source file.
- Replace the specific word with another word.
- Write the modified content to the destination file.
# Exercise 78: File Word Replacement # Step 1: Read the content of the source file def read_file(filename): with open(filename, 'r') as file: return file.read() # Step 2: Replace the specific word with another word def replace_word(text, old_word, new_word): return text.replace(old_word, new_word) # Step 3: Write the modified content to the destination file def write_modified_content(filename, modified_content): with open(filename, 'w') as file: file.write(modified_content) # Main function to execute the program def main(): source_filename = 'source.txt' # Update with the filename of your source file destination_filename = 'modified.txt' # Update with the filename of your destination file old_word = 'old_word' # Specify the word to replace new_word = 'new_word' # Specify the new word # Read content from source file text = read_file(source_filename) # Replace the specific word with another word modified_text = replace_word(text, old_word, new_word) # Write the modified content to the destination file write_modified_content(destination_filename, modified_text) print("Word replaced and written to destination file.") if __name__ == "__main__": main()
Exercise 79: File Content Filtering
Write a Python program that reads the content of a text file, filters out lines containing a specific keyword, and writes the filtered content to another file.
Steps:
- Read the content of the source file.
- Filter out lines containing the specific keyword.
- Write the filtered content to the destination file.
# Exercise: File Content Filtering
# Step 1: Read the content of the source file
def read_file(filename):
with open(filename, 'r') as file:
return file.readlines()
# Step 2: Filter out lines containing the specific keyword
def filter_content(lines, keyword):
filtered_lines = [line for line in lines if keyword in line]
return filtered_lines
# Step 3: Write the filtered content to the destination file
def write_filtered_content(filename, filtered_content):
with open(filename, 'w') as file:
file.writelines(filtered_content)
# Main function to execute the program
def main():
source_filename = 'source.txt' # Update with the filename of your source file
destination_filename = 'filtered.txt' # Update with the filename of your destination file
keyword = 'python' # Specify the keyword to filter lines
# Read content from source file
lines = read_file(source_filename)
# Filter out lines containing the specific keyword
filtered_lines = filter_content(lines, keyword)
# Write the filtered content to the destination file
write_filtered_content(destination_filename, filtered_lines)
print("Content filtered and written to destination file.")
if __name__ == "__main__":
main()
Exercise 80: File Line Sorting
Write a Python program that reads the content of a text file, sorts the lines alphabetically, and writes the sorted content to another file.
Steps:
- Read the content of the source file.
- Sort the lines alphabetically.
- Write the sorted content to the destination file.
# Exercise 80: File Line Sorting
# Step 1: Read the content of the source file
def read_file(filename):
with open(filename, 'r') as file:
return file.readlines()
# Step 2: Sort the lines alphabetically
def sort_lines(lines):
return sorted(lines)
# Step 3: Write the sorted content to the destination file
def write_sorted_content(filename, sorted_content):
with open(filename, 'w') as file:
file.writelines(sorted_content)
# Main function to execute the program
def main():
source_filename = 'source.txt' # Update with the filename of your source file
destination_filename = 'sorted.txt' # Update with the filename of your destination file
# Read content from source file
lines = read_file(source_filename)
# Sort the lines alphabetically
sorted_lines = sort_lines(lines)
# Write the sorted content to the destination file
write_sorted_content(destination_filename, sorted_lines)
print("Content sorted and written to destination file.")
if __name__ == "__main__":
main()



Post Comment