51 Python Programs
51 Python Programs
com
[Link]
Table of Contents
ABOUT AUTHOR – BIJAY KUMAR .......................................................................................... 4
1# PYTHON PROGRAM TO FIND THE EXPONENTIATION OF A NUMBER ................................ 5
2# PYTHON PROGRAM TO FIND REVERSE OF A NUMBER..................................................... 6
3# PYTHON PROGRAM TO CHECK IF A NUMBER IS A PRIME NUMBER .................................. 7
4# PYTHON PROGRAM TO FIND LARGEST OF THREE NUMBERS........................................... 9
5# PYTHON PROGRAM TO FIND SUM AND AVERAGE OF THREE NUMBERS ........................ 11
6# PYTHON PROGRAM TO FIND GCD AND LCM OF TWO NUMBERS ................................... 12
7# PYTHON PROGRAM TO FIND HCF AND LCM OF TWO NUMBERS ................................... 14
8# PYTHON PROGRAM FOR PALINDROME NUMBER .......................................................... 16
9# PYTHON PROGRAM FOR FIBONACCI SERIES ................................................................ 18
10# PYTHON PROGRAM FOR ARMSTRONG NUMBER ......................................................... 20
11# PYTHON PROGRAM FOR BINARY SEARCH .................................................................. 22
12# PYTHON PROGRAM FOR BUBBLE SORT ...................................................................... 25
13# PYTHON PROGRAM TO FIND AREA OF CIRCLE ............................................................ 27
14# PYTHON PROGRAM TO FIND AREA OF TRIANGLE ........................................................ 28
15# PYTHON PROGRAM TO FIND AREA OF SQUARE .......................................................... 29
16# PYTHON PROGRAM TO FIND EVEN OR ODD USING FUNCTION ................................... 31
17# PYTHON PROGRAM TO FIND EVEN OR ODD USING FUNCTION ................................... 32
18# PYTHON PROGRAM TO FIND REPEATED WORDS IN A STRING ..................................... 34
19# PYTHON PROGRAM FOR NUMBER GUESSING GAME .................................................. 37
20# PYTHON PROGRAM TO PRINT A STAR PATTERN ........................................................... 39
21# PYTHON PROGRAM TO PRINT DIAMOND PATTERN ...................................................... 43
22# PYTHON PROGRAM TO PRINT MULTIPLICATION TABLE ................................................ 44
23# PYTHON PROGRAM FOR MULTIPLICATION TABLES FOR NUMBERS 1 THROUGH 10 ..... 46
24# PYTHON PROGRAM FOR COMPOUND INTEREST ........................................................ 48
25# PYTHON PROGRAM TO CONVERT CELSIUS TO FAHRENHEIT ....................................... 52
26# PYTHON PROGRAM TO CONVERT FAHRENHEIT INTO CELSIUS.................................... 54
27# PYTHON PROGRAM TO CONVERT KILOMETERS TO MILES ........................................... 56
28# PYTHON PROGRAM TO CONVERT MILES TO KILOMETERS ........................................... 57
29# PYTHON PROGRAM TO CONVERT BITS TO MEGABYTES GIGABYTES AND TERABYTES ... 59
30# PYTHON PROGRAM TO CONVERT CENTIMETERS TO INCHES ...................................... 62
31# PYTHON PROGRAM TO CONVERT DAYS INTO YEARS WEEKS AND DAYS....................... 63
32# PYTHON PROGRAM TO CONVERT DEGREE TO RADIAN ............................................... 65
33# PYTHON PROGRAM TO CONVERT POUNDS TO KILOGRAMS ........................................ 67
34# PYTHON PROGRAM TO CONVERT LOWER CASE TO UPPER CASE ................................ 69
[Link]
def main():
# Prompt the user to enter the base and exponent
base = float(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
# Example usage
number = 1234
[Link]
reversed_number = reverse_number(number)
print(f"The reverse of {number} is {reversed_number}")
Explanation:
1. Extract the Last Digit: We use num % 10 to get the last digit of the
number.
2. Append the Digit: We multiply the current reversed_num by 10 and
add the extracted digit to it.
3. Remove the Last Digit: We use integer division num // 10 to remove
the last digit from the original number.
4. Loop Until Number is Zero: The loop continues until all digits are
processed.
This method ensures that the digits of the original number are reversed and
concatenated correctly to form the reversed number.
# Example usage
number = 29
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Explanation:
1. Check if Number is Less Than or Equal to 1: Prime numbers are
greater than 1. So, if num <= 1, the function returns False.
2. Check Divisors Up to the Square Root: We only need to check for
factors up to the square root of the number (int(num**0.5) + 1). This
is because a larger factor of the number would necessarily be paired
with a smaller factor that we would have already checked.
3. Check for Divisibility: We use a for loop to iterate from 2 up to the
square root of the number. If num % i == 0 for any i, the number is not
prime, and we return False.
4. Return True if No Divisors Found: If no divisors are found in the loop,
the number is prime, and we return True.
Example:
For the number 29:
• It is greater than 1.
• The square root of 29 is approximately 5.39, so we check divisors
from 2 to 5.
• 29 is not divisible by 2, 3, 4, or 5.
• Since no divisors are found, 29 is a prime number.
Here is the exact output:
[Link]
# Example usage
number1 = 10
number2 = 25
number3 = 20
largest_number = find_largest(number1, number2, number3)
print(f"The largest number among {number1}, {number2}, and {number3} is
{largest_number}")
Explanation:
1. Define the Function: The function find_largest takes three
arguments: num1, num2, and num3.
[Link]
# Example usage
number1 = 10
number2 = 20
number3 = 30
total_sum, average = sum_and_average(number1, number2, number3)
print(f"The sum of {number1}, {number2}, and {number3} is {total_sum}")
print(f"The average of {number1}, {number2}, and {number3} is {average}")
Explanation:
1. Define the Function: The function sum_and_average takes three
arguments: num1, num2, and num3.
2. Calculate the Sum: The sum of the three numbers is calculated using
the expression num1 + num2 + num3 and stored in the
variable total_sum.
3. Calculate the Average: The average is calculated by dividing
the total_sum by 3 and stored in the variable average.
4. Return the Results: The function returns both the total_sum and
the average.
Example:
For the numbers 10, 20, and 30:
• The sum is calculated as 10 + 20 + 30 = 60.
• The average is calculated as 60 / 3 = 20.
• The function returns 60 as the sum and 20 as the average.
Here is the exact output:
[Link]
# Example usage
number1 = 12
number2 = 15
gcd = calculate_gcd(number1, number2)
lcm = calculate_lcm(number1, number2)
print(f"The GCD of {number1} and {number2} is {gcd}")
print(f"The LCM of {number1} and {number2} is {lcm}")
[Link]
Explanation:
1. Import the math Module: We use Python's built-in math module to
calculate the GCD.
2. Calculate GCD:
• The function calculate_gcd uses [Link](num1, num2) to
compute the GCD of num1 and num2.
3. Calculate LCM:
• The function calculate_lcm first calculates the GCD using
the calculate_gcd function.
• The LCM is then calculated using the formula abs(num1 *
num2) // gcd. This formula works because the product of the
GCD and LCM of two numbers equals the product of the
numbers themselves.
4. Example Usage:
• For the numbers 12 and 15:
• The GCD is calculated as [Link](12, 15), which is 3.
• The LCM is calculated as abs(12 * 15) // 3, which is 60.
Example:
For the numbers 12 and 15:
• The GCD is 3.
• The LCM is 60.
Here is the exact output you can see in the screenshot below:
[Link]
# Example usage
number1 = 12
[Link]
number2 = 15
hcf = calculate_hcf(number1, number2)
lcm = calculate_lcm(number1, number2)
print(f"The HCF of {number1} and {number2} is {hcf}")
print(f"The LCM of {number1} and {number2} is {lcm}")
Explanation:
1. Import the math Module: The math module in Python provides a
built-in function to calculate the GCD.
2. Calculate HCF (GCD):
• The function calculate_hcf uses [Link](num1, num2) to
compute the HCF of num1 and num2.
3. Calculate LCM:
• The function calculate_lcm first calculates the HCF using
the calculate_hcf function.
• The LCM is then calculated using the formula abs(num1 *
num2) // hcf. This formula works because the product of the
HCF and LCM of two numbers equals the product of the
numbers themselves.
4. Example Usage:
• For the numbers 12 and 15:
• The HCF is calculated as [Link](12, 15), which is 3.
• The LCM is calculated as abs(12 * 15) // 3, which is 60.
Example:
For the numbers 12 and 15:
• The HCF is 3.
• The LCM is 60.
Here is the exact output in the screenshot below:
[Link]
# Example usage
number = 12321
if is_palindrome_number(number):
print(f"{number} is a palindrome number.")
else:
[Link]
Explanation:
1. Define the Function: The function is_palindrome_number takes a
single argument num, which is the number to be checked.
2. Convert Number to String:
• str_num = str(num): This converts the number to a string. This
step is necessary because checking for a palindrome involves
comparing the sequence of digits.
3. Check Palindrome:
• str_num == str_num[::-1]: This compares the string
representation of the number with its reverse. The slicing
operation str_num[::-1] creates a reversed copy of the string.
• If the string is equal to its reversed copy, the number is a
palindrome, and the function returns True. Otherwise, it
returns False.
4. Example Usage:
• The example number 12321 is converted to the string "12321".
• The reversed string is also "12321".
• Since they are equal, the number is identified as a palindrome.
Here is the exact output you can see in the screenshot below:
[Link]
# Example usage
n_terms = 10
fib_series = fibonacci_series(n_terms)
print(f"The first {n_terms} terms of the Fibonacci series are: {fib_series}")
[Link]
Explanation:
1. Define the Function: The function fibonacci_series takes a single
argument n, which specifies the number of terms in the Fibonacci
series to be generated.
2. Initialize the First Two Terms:
• fib_sequence = [0, 1]: This initializes the list with the first two
terms of the Fibonacci series, 0 and 1.
3. Generate the Fibonacci Series:
• The for loop starts from 2 and runs up to n-1, generating the
next terms of the series.
• next_term = fib_sequence[-1] + fib_sequence[-2]: This
calculates the next term by adding the last two terms in the
current sequence.
• fib_sequence.append(next_term): This appends the newly
calculated term to the sequence.
4. Return the Series:
• return fib_sequence[:n]: This returns the first n terms of the
Fibonacci series. The slicing is necessary in case n is less than
2, ensuring the function returns the correct number of terms.
5. Example Usage:
• For n_terms = 10, the function generates the first 10 terms of
the Fibonacci series.
• The output will be: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34].
Example:
For n_terms = 10:
• The first 10 terms of the Fibonacci series are [0, 1, 1, 2, 3, 5, 8, 13, 21,
34].
Here is the exact output:
[Link]
# Example usage
number = 153
if is_armstrong_number(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
[Link]
Explanation:
1. Define the Function: The function is_armstrong_number takes a
single argument num, which is the number to be checked.
2. Convert the Number to a String:
• num_str = str(num): This converts the number to a string to
easily iterate over each digit.
3. Calculate the Number of Digits:
• num_digits = len(num_str): This calculates the number of digits
in the number.
4. Initialize the Sum:
• sum_of_powers = 0: This initializes the sum of the digits raised
to the power of the number of digits.
5. Calculate the Sum of Powers:
• The for loop iterates over each digit in the string representation
of the number.
• sum_of_powers += int(digit) ** num_digits: This converts the
digit back to an integer, raises it to the power of num_digits, and
adds it to sum_of_powers.
6. Check if the Sum Equals the Original Number:
• return sum_of_powers == num: This checks if the sum of the
digits raised to the power of the number of digits is equal to the
original number. If true, the number is an Armstrong number.
7. Example Usage:
• For the number 153:
• The number of digits is 3.
• The sum of the digits raised to the power of 3 is (1^3 +
5^3 + 3^3 = 1 + 125 + 27 = 153).
• Since the sum equals the original number, 153 is an
Armstrong number.
[Link]
Example:
For the number 153:
• The sum of the digits raised to the power of the number of digits is
(1^3 + 5^3 + 3^3 = 153).
• Since the sum equals the original number, 153 is an Armstrong
number.
Here is the exact output in the screenshot below:
# Example usage
arr = [2, 3, 4, 10, 40]
target = 10
if result != -1:
print(f"Element {target} is present at index {result}.")
else:
print(f"Element {target} is not present in the array.")
Explanation:
1. Define the Function: The function binary_search takes two
arguments: arr (the sorted list of elements) and target (the element to
be searched).
2. Initialize Pointers:
• left is initialized to 0 (the start of the array).
• right is initialized to len(arr) - 1 (the end of the array).
3. Iterate Until the Search Space is Exhausted:
• The while loop continues as long as left is less than or equal
to right.
4. Calculate the Middle Index:
• mid = (left + right) // 2: This calculates the middle index of the
current search space.
5. Check if the Target is at the Middle:
[Link]
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print("Sorted array is:", sorted_arr)
Explanation
1. Outer Loop: The outer loop runs n times, where n is the length of the
array. This ensures that all elements are sorted.
2. Inner Loop: The inner loop runs from the start of the array to n-i-1.
This is because after each pass, the largest element moves to its
correct position, so we can ignore the last i elements in the
subsequent passes.
3. Comparison and Swap: During each pass, adjacent elements are
compared. If the current element is greater than the next element,
they are swapped.
This algorithm has a time complexity of (O(n^2)) in the worst and average
cases, making it inefficient for large lists. However, it is easy to understand
and implement, which makes it useful for educational purposes.
Here is the exact output:
[Link]
def calculate_area(radius):
area = [Link] * (radius ** 2)
return area
# Example usage
radius = float(input("Enter the radius of the circle: "))
area = calculate_area(radius)
print(f"The area of the circle with radius {radius} is {area:.2f}")
[Link]
Explanation
1. Import math module: This module provides access to the
mathematical constant ( \pi ) and other mathematical functions.
2. Define calculate_area function: This function takes the radius as an
argument, calculates the area using the formula ( \pi \times r^2 ), and
returns the result.
3. User Input: The program prompts the user to enter the radius of the
circle.
4. Calculate and Print Area: The program calculates the area using
the calculate_area function and prints the result formatted to two
decimal places.
Here is the exact output:
# Example usage
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = calculate_area(base, height)
print(f"The area of the triangle with base {base} and height {height} is
{area:.2f}")
Here is the exact output you can see in the screenshot below:
# Example usage
side = float(input("Enter the length of the side of the square: "))
area = calculate_area(side)
print(f"The area of the square with side length {side} is {area:.2f}")
Explanation
1. Define calculate_area function: This function takes the length of one
side of the square as an argument, calculates the area using the
formula ( \text{side}^2 ), and returns the result.
2. User Input: The program prompts the user to enter the length of the
side of the square.
3. Calculate and Print Area: The program calculates the area using
the calculate_area function and prints the result formatted to two
decimal places.
Example
Let's say the user inputs a side length of 5 units.
• The program will calculate the area as ( 5^2 = 25 ) square units.
• The output will be: "The area of the square with side length 5.0 is
25.00"
Here is the exact output in the screenshot below:
[Link]
# Example usage
number = int(input("Enter a number: "))
result = check_even_or_odd(number)
print(f"The number {number} is {result}.")
Explanation
1. Define check_even_or_odd function: This function takes a single
argument number.
• It uses the modulus operator % to check if the number is
divisible by 2.
• If number % 2 == 0, it returns "Even".
• Otherwise, it returns "Odd".
2. User Input: The program prompts the user to enter a number.
• The input function is used to get the user's input, which is then
converted to an integer using int().
3. Check and Print Result: The program calls the check_even_or_odd
function with the user's input and prints whether the number is even
or odd.
Example
Let's say the user inputs the number 7.
• The program will call check_even_or_odd(7).
[Link]
# Example usage
number = int(input("Enter a number: "))
result = check_even_or_odd(number)
print(f"The number {number} is {result}.")
Explanation
1. Define check_even_or_odd function: This function takes a single
argument number.
• It uses the modulus operator % to check if the number is
divisible by 2.
• If number % 2 == 0, it returns "Even".
• Otherwise, it returns "Odd".
2. User Input: The program prompts the user to enter a number.
• The input function is used to get the user's input, which is then
converted to an integer using int().
3. Check and Print Result: The program calls the check_even_or_odd
function with the user's input and prints whether the number is even
or odd.
Example
Let's say the user inputs the number 7.
• The program will call check_even_or_odd(7).
• Inside the function, it checks 7 % 2, which equals 1 (not 0), so it
returns "Odd".
• The output will be: "The number 7 is Odd."
Similarly, if the user inputs the number 8:
[Link]
return repeated_words
# Example usage
input_string = "This is a test. This test is only a test."
repeated_words = find_repeated_words(input_string)
print("Repeated words and their counts:", repeated_words)
Explanation
1. Define find_repeated_words function: This function takes
an input_string as an argument.
• It splits the string into words using the split() method, which by
default splits by whitespace.
2. Create a Dictionary to Count Words:
• It initializes an empty dictionary word_count to store the count
of each word.
• It iterates over each word in the list of words, converts each
word to lowercase (to make the counting case-insensitive), and
updates the word count in the dictionary.
3. Identify Repeated Words:
• It uses a dictionary comprehension to create a new
dictionary repeated_words that contains only the words that
have a count greater than 1.
4. Return Repeated Words: The function returns
the repeated_words dictionary.
Example
[Link]
def number_guessing_game():
# Generate a random number between 1 and 100
number_to_guess = [Link](1, 100)
while True:
# Prompt the user to enter a guess
guess = int(input("Guess a number between 1 and 100: "))
Explanation
1. Import random module: This module is used to generate a random
number.
2. Define number_guessing_game function: This function contains the
logic for the game.
[Link]
# Example usage
rows = int(input("Enter the number of rows: "))
print_right_angled_triangle(rows)
Explanation
1. Define print_right_angled_triangle Function:
• This function takes one argument, rows, which specifies the
number of rows in the triangle.
• It uses a for loop to iterate from 1 to rows (inclusive).
• In each iteration, it prints a string consisting of i asterisks ('*' *
i).
2. User Input:
• The program prompts the user to enter the number of rows for
the triangle.
[Link]
# Example usage
rows = int(input("Enter the number of rows: "))
print_pyramid(rows)
Explanation
1. Define print_pyramid Function:
• This function takes one argument, rows, which specifies the
number of rows in the pyramid.
• It uses a for loop to iterate from 1 to rows (inclusive).
• In each iteration, it prints leading spaces (' ' * (rows - i)) to
center the stars.
• It then prints the stars ('*' * (2 * i - 1)), where the number of
stars in each row is 2 * i - 1.
2. User Input:
• The program prompts the user to enter the number of rows for
the pyramid.
• The input is read as a string and then converted to an integer
using int().
[Link]
# Example usage
number = int(input("Enter the number for which you want the multiplication
table: "))
print_multiplication_table(number)
Explanation
1. Define print_multiplication_table Function:
• This function takes two arguments: number (the number for
which the multiplication table is to be printed) and up_to (the
range up to which the table should be printed, default is 10).
• It uses a for loop to iterate from 1 to up_to (inclusive).
• In each iteration, it calculates the product of number and i, and
prints it in the format number x i = product.
2. User Input:
• The program prompts the user to enter the number for which
they want the multiplication table.
• The input is read as a string and then converted to an integer
using int().
3. Print the Multiplication Table:
• The program calls the print_multiplication_table function with
the user-provided number.
• The function prints the multiplication table for the specified
number.
Example Output
If the user inputs 5, the output will be:
[Link]
# Example usage
print_all_multiplication_tables()
Explanation
1. Define print_all_multiplication_tables Function:
• This function takes one optional argument up_to (the range up
to which the tables should be printed, default is 10).
• It uses a nested for loop:
[Link]
Where:
• ( A ) is the amount of money accumulated after n years, including
interest.
• ( P ) is the principal amount (the initial amount of money).
• ( r ) is the annual interest rate (in decimal form).
• ( n ) is the number of times that interest is compounded per year.
• ( t ) is the time the money is invested for, in years.
The compound interest ( CI ) can be calculated as:
[ CI = A - P ]
Here is a Python program to calculate compound interest:
def calculate_compound_interest(principal, rate, times_compounded, years):
# Calculate the amount after the given number of years
amount = principal * (1 + rate / times_compounded) ** (times_compounded *
years)
# Example usage
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual interest rate (as a percentage): ")) /
100
times_compounded = int(input("Enter the number of times interest is compounded
per year: "))
years = float(input("Enter the number of years the money is invested for: "))
Explanation
1. Define calculate_compound_interest Function:
• This function takes four arguments:
• principal: The initial amount of money (P).
[Link]
# Example usage
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius} degrees Celsius is equal to {fahrenheit:.2f} degrees
Fahrenheit.")
Explanation
1. Define celsius_to_fahrenheit Function:
• This function takes a temperature in Celsius as an argument.
[Link]
# Example usage
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit} degrees Fahrenheit is equal to {celsius:.2f} degrees
Celsius.")
Explanation
1. Define fahrenheit_to_celsius Function:
• This function takes a temperature in Fahrenheit as an
argument.
• It applies the conversion formula ((\text{Fahrenheit} - 32)
\times \frac{5}{9}) to calculate the equivalent temperature in
Celsius.
[Link]
# Example usage
kilometers = float(input("Enter distance in kilometers: "))
miles = kilometers_to_miles(kilometers)
print(f"{kilometers} kilometers is equal to {miles:.2f} miles.")
Explanation
1. Define kilometers_to_miles Function:
• This function takes a distance in kilometers as an argument.
• It applies the conversion factor ( \text{Kilometers} \times
0.621371 ) to calculate the equivalent distance in miles.
• It returns the calculated distance in miles.
2. User Input:
• The program prompts the user to enter a distance in
kilometers.
• The input is read as a string and then converted to a floating-
point number using float().
3. Convert and Print:
• The program calls the kilometers_to_miles function with the
user-provided distance in kilometers.
• It prints the result, formatted to two decimal places.
Example
Let's say the user inputs a distance of 10 kilometers.
[Link]
# Example usage
miles = float(input("Enter distance in miles: "))
kilometers = miles_to_kilometers(miles)
print(f"{miles} miles is equal to {kilometers:.2f} kilometers.")
[Link]
Explanation
1. Define miles_to_kilometers Function:
• This function takes a distance in miles as an argument.
• It applies the conversion factor ( \text{Miles} \times 1.60934 ) to
calculate the equivalent distance in kilometers.
• It returns the calculated distance in kilometers.
2. User Input:
• The program prompts the user to enter a distance in miles.
• The input is read as a string and then converted to a floating-
point number using float().
3. Convert and Print:
• The program calls the miles_to_kilometers function with the
user-provided distance in miles.
• It prints the result, formatted to two decimal places.
Example
Let's say the user inputs a distance of 5 miles.
• The program will call miles_to_kilometers(5).
• Inside the function, it calculates ( 5 \times 1.60934 = 8.0467 )
kilometers.
• The output will be: "5.0 miles is equal to 8.05 kilometers."
Here is the exact output:
[Link]
# Example usage
bits = float(input("Enter the number of bits: "))
megabytes, gigabytes, terabytes = bits_to_other_units(bits)
print(f"{bits} bits is equal to {megabytes:.6f} megabytes, {gigabytes:.6f}
gigabytes, and {terabytes:.6f} terabytes.")
Explanation
1. Define bits_to_other_units Function:
• This function takes the number of bits as an argument.
• It converts bits to bytes by dividing by 8.
• It converts bytes to kilobytes by dividing by 1024.
• It converts kilobytes to megabytes by dividing by 1024.
• It converts megabytes to gigabytes by dividing by 1024.
• It converts gigabytes to terabytes by dividing by 1024.
• It returns the values in megabytes, gigabytes, and terabytes.
2. User Input:
• The program prompts the user to enter a number of bits.
• The input is read as a string and then converted to a floating-
point number using float().
3. Convert and Print:
• The program calls the bits_to_other_units function with the
user-provided number of bits.
[Link]
# Example usage
centimeters = float(input("Enter length in centimeters: "))
inches = centimeters_to_inches(centimeters)
print(f"{centimeters} centimeters is equal to {inches:.2f} inches.")
Explanation
1. Define centimeters_to_inches Function:
• This function takes a length in centimeters as an argument.
• It applies the conversion factor ( \text{Centimeters} \times
0.393701 ) to calculate the equivalent length in inches.
• It returns the calculated length in inches.
2. User Input:
• The program prompts the user to enter a length in centimeters.
• The input is read as a string and then converted to a floating-
point number using float().
3. Convert and Print:
• The program calls the centimeters_to_inches function with the
user-provided length in centimeters.
• It prints the result, formatted to two decimal places.
Example
Let's say the user inputs a length of 100 centimeters.
• The program will call centimeters_to_inches(100).
[Link]
# Example usage
total_days = int(input("Enter the number of days: "))
years, weeks, days_left = convert_days(total_days)
print(f"{total_days} days is equal to {years} years, {weeks} weeks, and
{days_left} days.")
Explanation
1. Define convert_days Function:
• This function takes a total number of days as an argument.
• It calculates the number of years by performing integer division
of the total days by 365.
• It calculates the remaining days after extracting the years using
the modulus operator %.
• It calculates the number of weeks from the remaining days by
performing integer division by 7.
• It calculates the remaining days after extracting the weeks
using the modulus operator %.
• It returns the number of years, weeks, and remaining days.
2. User Input:
• The program prompts the user to enter the total number of
days.
• The input is read as a string and then converted to an integer
using int().
3. Convert and Print:
• The program calls the convert_days function with the user-
provided number of days.
• It prints the result, showing the equivalent number of years,
weeks, and days.
[Link]
Example
Let's say the user inputs 400 days.
• The program will call convert_days(400).
• Inside the function, it performs the following calculations:
• ( \text{Years} = 400 // 365 = 1 )
• ( \text{Remaining Days} = 400 % 365 = 35 )
• ( \text{Weeks} = 35 // 7 = 5 )
• ( \text{Days Left} = 35 % 7 = 0 )
• The output will be: "400 days is equal to 1 years, 5 weeks, and 0
days."
Here is the exact output:
In Python, you can use the math module which provides the constant
[Link] for the value of (\pi).
Here is a Python program to perform this conversion:
import math
def degrees_to_radians(degrees):
radians = degrees * ([Link] / 180)
return radians
# Example usage
degrees = float(input("Enter angle in degrees: "))
radians = degrees_to_radians(degrees)
print(f"{degrees} degrees is equal to {radians:.6f} radians.")
Explanation
1. Import math Module:
• The math module provides mathematical functions and
constants, including [Link].
2. Define degrees_to_radians Function:
• This function takes an angle in degrees as an argument.
• It applies the conversion formula (\text{Degrees} \times
\frac{\pi}{180}) to calculate the equivalent angle in radians.
• It returns the calculated angle in radians.
3. User Input:
• The program prompts the user to enter an angle in degrees.
• The input is read as a string and then converted to a floating-
point number using float().
4. Convert and Print:
• The program calls the degrees_to_radians function with the
user-provided angle in degrees.
• It prints the result, formatted to six decimal places.
Example
Let's say the user inputs an angle of 180 degrees.
[Link]
# Example usage
pounds = float(input("Enter weight in pounds: "))
kilograms = pounds_to_kilograms(pounds)
[Link]
Explanation
1. Define pounds_to_kilograms Function:
• This function takes a weight in pounds as an argument.
• It applies the conversion factor ( \text{Pounds} \times 0.453592
) to calculate the equivalent weight in kilograms.
• It returns the calculated weight in kilograms.
2. User Input:
• The program prompts the user to enter a weight in pounds.
• The input is read as a string and then converted to a floating-
point number using float().
3. Convert and Print:
• The program calls the pounds_to_kilograms function with the
user-provided weight in pounds.
• It prints the result, formatted to two decimal places.
Example
Let's say the user inputs a weight of 150 pounds.
• The program will call pounds_to_kilograms(150).
• Inside the function, it calculates ( 150 \times 0.453592 = 68.0388 )
kilograms.
• The output will be: "150.0 pounds is equal to 68.04 kilograms."
Here is the exact output in the screenshot below:
[Link]
# Example usage
input_string = input("Enter a string in lowercase: ")
uppercase_string = convert_to_uppercase(input_string)
print(f"The string in uppercase is: {uppercase_string}")
Explanation
1. Define convert_to_uppercase Function:
• This function takes a string input_string as an argument.
[Link]
# Example usage
input_string = input("Enter a string in uppercase: ")
lowercase_string = convert_to_lowercase(input_string)
print(f"The string in lowercase is: {lowercase_string}")
[Link]
Explanation
1. Define convert_to_lowercase Function:
• This function takes a string input_string as an argument.
• It uses the lower() method to convert all characters in the string
to lowercase.
• It returns the converted string.
2. User Input:
• The program prompts the user to enter a string in uppercase.
• The input is read as a string using the input() function.
3. Convert and Print:
• The program calls the convert_to_lowercase function with the
user-provided string.
• It prints the result, showing the string converted to lowercase.
Example
Let's say the user inputs the string "HELLO WORLD".
• The program will call convert_to_lowercase("HELLO WORLD").
• Inside the function, it converts the string to lowercase using
the lower() method: "HELLO WORLD".lower() results in "hello world".
• The output will be: "The string in lowercase is: hello world".
Here is the exact screenshot:
[Link]
return vowel_count
# Example usage
input_string = input("Enter a string: ")
vowel_count = count_vowels(input_string)
print(f"The number of vowels in the string is: {vowel_count}")
[Link]
Explanation
1. Define count_vowels Function:
• This function takes a string input_string as an argument.
• It defines a set of vowels vowels = set("aeiouAEIOU") to include
both lowercase and uppercase vowels.
• It initializes a counter vowel_count to zero.
2. Iterate Through the String:
• The function iterates through each character in the string using
a for loop.
• For each character, it checks if the character is in the set of
vowels.
• If the character is a vowel, it increments the vowel_count by 1.
3. Return the Count:
• After iterating through the entire string, the function returns the
total count of vowels.
4. User Input:
• The program prompts the user to enter a string.
• The input is read as a string using the input() function.
5. Count and Print:
• The program calls the count_vowels function with the user-
provided string.
• It prints the result, showing the number of vowels in the string.
Example
Let's say the user inputs the string "Hello World".
• The program will call count_vowels("Hello World").
• Inside the function, it iterates through each character:
• 'H' (not a vowel)
[Link]
# Example usage
binary_str = input("Enter a binary number: ")
decimal_number = binary_to_decimal(binary_str)
print(f"The decimal equivalent of binary {binary_str} is {decimal_number}.")
Explanation
• The int function can convert a binary string to a decimal number by
specifying the base as 2.
• int(binary_str, 2) converts the binary string binary_str to its decimal
equivalent.
• The function binary_to_decimal takes a binary string as an argument,
uses the int function to perform the conversion, and returns the
decimal number.
Let's say the user inputs the binary number "1010".
• Using the int Function:
• The program calls binary_to_decimal("1010").
• Inside the function, int("1010", 2) converts "1010" to 10.
• The output will be: "The decimal equivalent of binary 1010 is
10."
Here is the exact output in the screenshot below:
[Link]
# Example usage
original_price = float(input("Enter the original price: "))
[Link]
Explanation
1. Define calculate_discounted_amount Function:
• This function takes two
arguments: original_price and discount_percentage.
• It calculates the discount amount using the formula: [
\text{Discount Amount} = \left( \frac{\text{Original Price} \times
\text{Discount Percentage}}{100} \right) ]
• It calculates the discounted price by subtracting the discount
amount from the original price: [ \text{Discounted Price} =
\text{Original Price} - \text{Discount Amount} ]
• It returns both the discounted price and the discount amount.
2. User Input:
• The program prompts the user to enter the original price of the
item.
• The input is read as a string and then converted to a floating-
point number using float().
• The program prompts the user to enter the discount
percentage.
• The input is read as a string and then converted to a floating-
point number using float().
3. Calculate and Print:
• The program calls the calculate_discounted_amount function
with the user-provided original price and discount percentage.
• It prints the discount amount and the discounted price,
formatted to two decimal places.
Example
[Link]
Let's say the user inputs an original price of $100 and a discount
percentage of 20%.
• The program will call calculate_discounted_amount(100, 20).
• Inside the function:
• It calculates the discount amount: [ \text{Discount Amount} =
\left( \frac{100 \times 20}{100} \right) = 20 ]
• It calculates the discounted price: [ \text{Discounted Price} =
100 - 20 = 80 ]
• The output will be:
• The discount amount is: 20.00
The discounted price is: 80.00
Here is exact output in the screenshot below:
# Example usage
cost = float(input("Enter the cost of the asset: "))
salvage_value = float(input("Enter the salvage value of the asset: "))
useful_life = float(input("Enter the useful life of the asset (in years): "))
Explanation
1. Define calculate_depreciation Function:
• This function takes three arguments: cost, salvage_value,
and useful_life.
• It calculates the annual depreciation expense using the
formula: [ \text{Depreciation Expense} = \frac{\text{Cost of
Asset} - \text{Salvage Value}}{\text{Useful Life}} ]
• It returns the calculated annual depreciation expense.
2. User Input:
• The program prompts the user to enter the cost of the asset.
[Link]
# Example usage
weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in meters: "))
return "Underweight"
elif 18.5 <= bmi < 24.9:
return "Normal weight"
elif 25 <= bmi < 29.9:
return "Overweight"
else:
return "Obesity"
category = categorize_bmi(bmi)
print(f"Your BMI category is: {category}")
Explanation
1. Define calculate_bmi Function:
• This function takes two arguments: weight (in kilograms)
and height (in meters).
• It calculates BMI using the formula: [ \text{BMI} =
\frac{\text{weight}}{\text{height}^2} ]
• It returns the calculated BMI.
2. User Input:
• The program prompts the user to enter their weight in
kilograms.
• The input is read as a string and then converted to a floating-
point number using float().
• The program prompts the user to enter their height in meters.
• The input is read as a string and then converted to a floating-
point number using float().
3. Calculate and Print:
• The program calls the calculate_bmi function with the user-
provided weight and height.
• It prints the BMI, formatted to two decimal places.
4. Optional: Categorize the BMI Result:
• The categorize_bmi function takes the BMI value as an
argument.
[Link]
# Example usage
x1 = float(input("Enter the x-coordinate of the first point: "))
y1 = float(input("Enter the y-coordinate of the first point: "))
x2 = float(input("Enter the x-coordinate of the second point: "))
y2 = float(input("Enter the y-coordinate of the second point: "))
Explanation
1. Import math Module:
• The math module provides access to mathematical functions,
including [Link] for square root calculation.
2. Define calculate_distance Function:
• This function takes four arguments: the (x) and (y) coordinates
of the first point ((x1, y1)) and the (x) and (y) coordinates of the
second point ((x2, y2)).
• It calculates the distance using the Euclidean distance
formula: [ d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} ]
• It returns the calculated distance.
3. User Input:
• The program prompts the user to enter the (x) and (y)
coordinates of the first point.
• The inputs are read as strings and then converted to floating-
point numbers using float().
[Link]
• The program prompts the user to enter the (x) and (y)
coordinates of the second point.
• The inputs are read as strings and then converted to floating-
point numbers using float().
4. Calculate and Print:
• The program calls the calculate_distance function with the
user-provided coordinates.
• It prints the distance, formatted to two decimal places.
Example
Let's say the user inputs the following coordinates:
• First point: ((3, 4))
• Second point: ((6, 8))
• The program will call calculate_distance(3, 4, 6, 8).
• Inside the function:
• It calculates the distance: [ d = \sqrt{(6 - 3)^2 + (8 - 4)^2} =
\sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5 ]
• The output will be:
The distance between the points (3.0, 4.0) and (6.0, 8.0) is 5.00
return day_of_week
# Example usage
year = int(input("Enter year (e.g., 2024): "))
month = int(input("Enter month (1-12): "))
day = int(input("Enter day (1-31): "))
Explanation
1. Import datetime Module:
• The datetime module provides classes for manipulating dates
and times.
2. Define find_day_of_week Function:
• This function takes three arguments: year, month, and day.
• It creates a date object for the given date
using [Link](year, month, day).
• It uses the weekday() method of the date object to get the day
of the week as an index (0 for Monday, 6 for Sunday).
• It defines a list days_of_week containing the names of the days
of the week.
• It retrieves the name of the day corresponding to the index
using days_of_week[day_of_week_index].
• It returns the name of the day.
3. User Input:
[Link]
• The program prompts the user to enter the year, month, and
day.
• The inputs are read as strings and then converted to integers
using int().
4. Find and Print:
• The program calls the find_day_of_week function with the user-
provided year, month, and day.
• It prints the day of the week for the given date.
Example
Let's say the user inputs the following date:
• Year: 2024
• Month: 10
• Day: 29
• The program will call find_day_of_week(2024, 10, 29).
• Inside the function:
• It creates a date object for 2024-10-29.
• It uses the weekday() method to get the day of the week index,
which is 1 (Tuesday).
• It retrieves the name "Tuesday" from the days_of_week list.
• The output will be:
The day of the week for 2024-10-29 is Tuesday.
Here is the exact output:
[Link]
return percentage
# Example usage
marks = []
for i in range(1, 6):
mark = float(input(f"Enter marks for subject {i} (out of 100): "))
[Link](mark)
percentage = calculate_percentage(marks)
print(f"The percentage of marks obtained is: {percentage:.2f}%")
Explanation
1. Define calculate_percentage Function:
• This function takes a list of marks for the five subjects.
• It calculates the total marks obtained using the sum() function.
• It calculates the maximum possible marks by multiplying the
number of subjects by 100 (assuming each subject is out of
100 marks).
• It calculates the percentage using the formula: [
\text{Percentage} = \left( \frac{\text{Total Marks
Obtained}}{\text{Maximum Possible Marks}} \right) \times 100 ]
• It returns the calculated percentage.
2. User Input:
• The program prompts the user to enter the marks for each of
the five subjects.
• The inputs are read as strings and then converted to floating-
point numbers using float().
• The marks are stored in a list called marks.
3. Calculate and Print:
[Link]
return result
# Example usage
base = float(input("Enter the base number: "))
exponent = float(input("Enter the exponent: "))
Explanation
1. Define power Function:
• This function takes two arguments: base (the base number)
and exponent (the exponent to which the base number is
raised).
• It calculates the power using the ** operator: [ \text{result} =
\text{base} ** \text{exponent} ]
• It returns the calculated result.
2. User Input:
• The program prompts the user to enter the base number.
• The input is read as a string and then converted to a floating-
point number using float().
• The program prompts the user to enter the exponent.
• The input is read as a string and then converted to a floating-
point number using float().
3. Calculate and Print:
• The program calls the power function with the user-provided
base and exponent.
• It prints the result, formatted to two decimal places.
Example
Let's say the user inputs the following values:
• Base number: 2
• Exponent: 3
[Link]
# Example usage
dividend = int(input("Enter the dividend: "))
divisor = int(input("Enter the divisor: "))
Explanation
1. Define find_quotient_and_remainder Function:
• This function takes two arguments: dividend (the number to be
divided) and divisor (the number by which to divide).
• It calculates the quotient using the // operator (integer
division): [ \text{quotient} = \text{dividend} // \text{divisor} ]
• It calculates the remainder using the % operator (modulus): [
\text{remainder} = \text{dividend} % \text{divisor} ]
• It returns both the quotient and the remainder.
2. User Input:
• The program prompts the user to enter the dividend.
• The input is read as a string and then converted to an integer
using int().
• The program prompts the user to enter the divisor.
• The input is read as a string and then converted to an integer
using int().
3. Calculate and Print:
• The program calls the find_quotient_and_remainder function
with the user-provided dividend and divisor.
[Link]
# Example usage
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Explanation
1. Define is_leap_year Function:
• This function takes one argument: year.
• It checks if the year is a leap year using the conditions:
• The year is divisible by 4 and not divisible by 100, or
• The year is divisible by 400.
• If either condition is met, the function returns True, indicating it
is a leap year.
• Otherwise, it returns False.
[Link]
2. User Input:
• The program prompts the user to enter a year.
• The input is read as a string and then converted to an integer
using int().
3. Check and Print:
• The program calls the is_leap_year function with the user-
provided year.
• It prints whether the year is a leap year or not based on the
function's return value.
Example
Let's say the user inputs the year 2024.
• The program will call is_leap_year(2024).
• Inside the function:
• It checks the conditions:
• 2024 is divisible by 4 (2024 % 4 == 0 is True).
• 2024 is not divisible by 100 (2024 % 100 != 0 is True).
• Since both conditions are met, the function returns True.
• The output will be:
• 2024 is a leap year.
Let's consider another example where the user inputs the year 1900.
• The program will call is_leap_year(1900).
• Inside the function:
• It checks the conditions:
• 1900 is divisible by 4 (1900 % 4 == 0 is True).
• 1900 is divisible by 100 (1900 % 100 == 0 is True).
• 1900 is not divisible by 400 (1900 % 400 != 0 is True).
[Link]
def get_current_date_time():
# Get the current date and time
now = [Link]()
return current_date_time
# Example usage
current_date_time = get_current_date_time()
print(f"The current date and time is: {current_date_time}")
Explanation
1. Import datetime Module:
• The datetime module provides classes for manipulating dates
and times.
• Specifically, [Link]() returns the current local date and
time.
2. Define get_current_date_time Function:
• This function gets the current date and time
using [Link]().
• It formats the date and time as a string using
the strftime method, which formats a datetime object to a
string according to the specified format codes.
• The format "%Y-%m-%d %H:%M:%S" represents:
• %Y: Year with century (e.g., 2024)
• %m: Month as a zero-padded decimal number (e.g., 01
for January)
• %d: Day of the month as a zero-padded decimal number
(e.g., 01)
• %H: Hour (24-hour clock) as a zero-padded decimal
number (e.g., 14 for 2 PM)
• %M: Minute as a zero-padded decimal number (e.g., 30)
• %S: Second as a zero-padded decimal number (e.g., 59)
• It returns the formatted current date and time as a string.
3. Get and Print Current Date and Time:
[Link]
# Example usage
date1 = input("Enter the first date (YYYY-MM-DD): ")
date2 = input("Enter the second date (YYYY-MM-DD): ")
Explanation
1. Import date Class from datetime Module:
• The date class is used to create date objects.
2. Define days_between_dates Function:
• This function takes two arguments: date1 and date2, which are
strings representing the dates in the format YYYY-MM-DD.
• It converts the input strings to date objects using
the date class:
• date(*map(int, [Link]('-'))) splits the string by the
hyphen, maps each part to an integer, and unpacks the
integers as arguments to the date constructor.
[Link]
def calculate_age(birthdate):
# Get today's date
today = [Link]()
# Adjust the age if the birthdate has not occurred yet this year
if ([Link], [Link]) < ([Link], [Link]):
age -= 1
return age
# Example usage
birth_year = int(input("Enter your birth year (e.g., 1990): "))
birth_month = int(input("Enter your birth month (1-12): "))
birth_day = int(input("Enter your birth day (1-31): "))
Explanation
1. Import date Class from datetime Module:
• The date class is used to create date objects.
2. Define calculate_age Function:
• This function takes one argument: birthdate, which is
a date object representing the person's date of birth.
• It gets today's date using [Link]().
• It calculates the initial age by subtracting the birth year from
the current year: [ \text{age} = \text{[Link]} -
\text{[Link]} ]
• It adjusts the age if the birthdate has not occurred yet this year
by checking if today's month and day are less than the
birthdate's month and day: [ \text{if ([Link], [Link]) <
([Link], [Link]):} ] [ \text{age} -= 1 ]
• It returns the calculated age.
3. User Input:
• The program prompts the user to enter their birth year, month,
and day.
• The inputs are read as strings and then converted to integers
using int().
[Link]
def print_yesterday_today_tomorrow():
# Get today's date
today = [Link]()
# Example usage
print_yesterday_today_tomorrow()
Explanation
1. Import date and timedelta Classes from datetime Module:
• The date class is used to create date objects representing
specific dates.
• The timedelta class is used to represent the difference
between two dates or to perform date arithmetic.
2. Define print_yesterday_today_tomorrow Function:
• This function calculates and prints the dates for yesterday,
today, and tomorrow.
• It gets today's date using [Link]().
• It calculates yesterday's date by subtracting one day from
today's date using timedelta(days=1): [ \text{yesterday} =
\text{today} - \text{timedelta(days=1)} ]
• It calculates tomorrow's date by adding one day to today's date
using timedelta(days=1): [ \text{tomorrow} = \text{today} +
\text{timedelta(days=1)} ]
• It prints the calculated dates.
[Link]
3. Example Usage:
• The program calls
the print_yesterday_today_tomorrow function to print the dates
for yesterday, today, and tomorrow.
Example Output
When you run the program, it will output the dates for yesterday, today, and
tomorrow. For example, if today is October 29, 2024, the output will be:
Yesterday's date was: 2024-10-28
Today's date is: 2024-10-29
Tomorrow's date will be: 2024-10-30
Here is the exact output:
[Link]
def print_days_of_the_week():
# Get the day names from the calendar module
days_of_week = list(calendar.day_name)
# Example usage
print_days_of_the_week()
Explanation
1. Import calendar Module:
• The calendar module provides functions and classes for
working with dates and calendars.
2. Define print_days_of_the_week Function:
• This function retrieves the names of the days of the week
from calendar.day_name, which is an iterable containing the
names of the days of the week.
• It converts calendar.day_name to a list called days_of_week.
• It uses a for loop to iterate over each element in
the days_of_week list.
• Inside the loop, it prints each day.
3. Example Usage:
• The program calls the print_days_of_the_week function to print
the days of the week.
[Link]
Example Output
When you run the program, it will output the same result as the previous
method:
• Monday
• Tuesday
• Wednesday
• Thursday
• Friday
• Saturday
• Sunday
You can see the exact output:
[Link]
CONCLUSION
I hope you liked all these Python programs. Do check out more Python
tutorials on our website: [Link]