Python Programming Exercises: Practical Code Examples

Python Programming Exercises

1. Age Calculator: Year of Turning 100

Write a program that accepts a name and age, then prints the year the person will turn 100 years old.

from datetime import datetime

name = input("What is your name? ")
age = int(input("How old are you?\n"))

current_year = datetime.now().year
hundred = current_year + (100 - age)

print("Hello %s! You are %s years old. You will turn 100 years old in %s." % (name, age, hundred))

2. Even or Odd Number Checker

Write a program that accepts a number from the user and determines whether it is even or odd.

num = int(input("Enter a number: "))

mod = num % 2

if mod > 0:
    print("This is an odd number.")
else:
    print("This is an even number.")

3. Armstrong Number Checker

Write a function to check whether the input value is an Armstrong number.

num = int(input("Enter a number: "))
sum = 0
temp = num

while temp > 0:
    digit = temp % 10
    sum += digit ** 3
    temp //= 10

if num == sum:
    print(num, "is an Armstrong number")
else:
    print(num, "is not an Armstrong number")

4. SGPI to Grade Converter

Write a program that accepts the SGPI from the user and prints the corresponding grade.

def get_grade(sgpi):
    if 9.00 <= sgpi <= 10.00:
        return "O"
    elif 8.00 <= sgpi < 9.00:
        return "A+"
    elif 7.00 <= sgpi < 8.00:
        return "A"
    elif 6.00 <= sgpi < 7.00:
        return "B+"
    elif 5.50 <= sgpi < 6.00:
        return "B"
    elif 5.00 <= sgpi < 5.50:
        return "C"
    elif 4.00 <= sgpi < 5.00:
        return "P"
    else:
        return "F"

if __name__ == "__main__":
    try:
        sgpi_input = float(input("Enter your SGPI: "))

        if not 0.00 <= sgpi_input <= 10.00:
            print("Invalid input. Please enter an SGPI between 0 and 10.")
        else:
            grade = get_grade(sgpi_input)
            print(f"Your grade is: {grade}")

    except ValueError:
        print("Invalid input. Please enter a numeric SGPI value.")

5. Palindrome Number Checker

Write a program to check whether a number is a palindrome or not.

num = int(input("Enter a number: "))
total = 0
n = num

while num != 0:
    rem = num % 10
    total = total * 10 + rem
    num = num // 10

if total == n:
    print(n, "is a palindrome")
else:
    print(n, "is not a palindrome")

6. Recursive Factorial Function

Write a program using a recursive function to print the factorial of a given number.

def recur_factorial(n):
    if n == 1 or n == 0:
        return 1
    else:
        return n * recur_factorial(n - 1)

num = int(input("Enter a number: "))

if num < 0:
    print("Sorry, factorial does not exist for negative numbers.")
elif num == 0:
    print("The factorial of 0 is 1.")
else:
    print("The factorial of", num, "is", recur_factorial(num))

7. Lambda Function: Check Starting Character

Write a program using a lambda function that checks whether a given string starts with a specific character.

starts_with = lambda x: True if x.startswith('J') else False

print(starts_with('Java'))
print(starts_with('Python'))

8. Count Words and Characters in a String

Write a program to compute the number of characters and words in a string.

s = "Python programming language"

res = len(s.split())
print("The number of words in the string is: " + str(res))

print("The number of characters in the string is:", len(s))

9. Check for Common Elements in Two Lists

Write a program that takes two lists and returns True if they have at least one common member.

def common_data(list1, list2):
    result = False

    for x in list1:
        for y in list2:
            if x == y:
                result = True
                return result

    return result

print(common_data([1, 2, 3, 4, 5], [5, 6, 7, 8, 9]))
print(common_data([1, 2, 3, 4, 5], [6, 7, 8, 9]))

10(i). Read an Entire Text File

Write a program to read an entire text file.

def file_read(fname):
    txt = open(fname)
    print(txt.read())
    txt.close()

file_read("text.txt")

10(ii). Write Text to a File and Display It

Write a program to write text into a file, then display the written text.

def file_read(fname):
    with open(fname, "w") as myfile:
        myfile.write("Python Exercises\n")
        myfile.write("Java Exercises")

    with open(fname, "r") as txt:
        print(txt.read())

file_read("abc.txt")