Python All Exercises & Assignments

Python program to add two numbers

Description: Write a Python program that takes two numbers from the user and prints their sum.

Rules and hints:

  • Use input() to read the numbers.
  • input() gives a string, so convert it with int() (or float() for decimals).

Python program to add two numbers

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

total = num1 + num2
print("Sum =", total)

Output:

Tutorials Class - Output Window

Enter first number: 12
Enter second number: 8
Sum = 20

How it works

  • The two input() calls read what the user types, as text.
  • int() converts the text to a whole number. Without it, "12" + "8" would give 128.
  • The sum is stored in total and printed.

Learn more in Python input() Function and Python Type Casting.

Python program to swap two variables

Description: Write a Python program to swap the values of two variables.

Rules and hints:

  • Do it first with a third (temporary) variable.
  • Then do it the Python way, in one line.

Python program to swap two variables

a = 10
b = 20
print("Before swap: a =", a, "b =", b)

a, b = b, a

print("After swap: a =", a, "b =", b)

Output:

Tutorials Class - Output Window

Before swap: a = 10 b = 20
After swap: a = 20 b = 10

How it works

  • The line a, b = b, a builds a tuple (b, a) and unpacks it into a and b.
  • In many other languages you need a third variable: temp = a, a = b, b = temp. That also works in Python.
  • Swapping works with any type, not only numbers.

Python program to find the area of a circle

Description: Write a Python program to calculate the area of a circle when the radius is 5.

Rules and hints:

  • Formula: area = pi x radius x radius.
  • Use math.pi for the value of pi.
  • Round the answer to 2 decimal places with round().

Python program for the area of a circle

import math

radius = 5
area = math.pi * radius ** 2

print("Area of the circle:", round(area, 2))

Output:

Tutorials Class - Output Window

Area of the circle: 78.54

How it works

  • radius ** 2 means radius to the power 2.
  • math.pi is 3.141592653589793, so the exact area is 78.53981633974483.
  • round(area, 2) keeps two digits after the decimal point.

See also Python Modules to learn about import.

Python program to convert Celsius to Fahrenheit

Description: Write a Python program to convert temperature from Celsius to Fahrenheit.

Rules and hints:

  • Formula: Fahrenheit = Celsius x 9 / 5 + 32.
  • Use an f-string to print the result.

Python program to convert Celsius to Fahrenheit

def to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32

for c in (0, 100):
    f = to_fahrenheit(c)
    print(f"{c} C = {f} F")

Output:

Tutorials Class - Output Window

0 C = 32.0 F
100 C = 212.0 F

How it works

  • The function takes a Celsius value and returns the Fahrenheit value.
  • The loop tests two famous values: water freezes at 0 C (32 F) and boils at 100 C (212 F).
  • The / operator always returns a float, that is why we see 32.0.

Read What are f-strings? and Python Functions.

Python program to check even or odd number

Description: Write a Python program to check whether a number is even or odd.

Rules and hints:

  • A number is even if it is divisible by 2.
  • Use the modulus operator %, which gives the remainder.

Python program to check even or odd

for number in (4, 7):
    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")

Output:

Tutorials Class - Output Window

4 is even
7 is odd

How it works

  • 4 % 2 is 0, so 4 is even.
  • 7 % 2 is 1, so the else part runs and 7 is odd.
  • Negative numbers also work, because -3 % 2 is 1 in Python.

Learn the basics in Python Conditional Statements.

Python program to find the largest of three numbers

Description: Write a Python program to find the largest of three numbers.

Rules and hints:

  • First use if, elif and else.
  • Then try the built-in max() function.

Python program to find the largest of three numbers

a = 25
b = 78
c = 42

if a >= b and a >= c:
    largest = a
elif b >= a and b >= c:
    largest = b
else:
    largest = c

print("Largest number is", largest)
print("Using max():", max(a, b, c))

Output:

Tutorials Class - Output Window

Largest number is 78
Using max(): 78

How it works

  • The first condition checks if a is bigger than or equal to both others.
  • If not, the elif checks b. If both fail, c must be the largest.
  • max() does all this work in one call, so use it in real programs.

Python program to check leap year

Description: Write a Python program to check whether a year is a leap year.

Rules and hints:

  • A year is a leap year if it is divisible by 4 but not by 100.
  • A year divisible by 400 is also a leap year.

Python program to check a leap year

def is_leap(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

for year in (2024, 1900, 2000, 2023):
    if is_leap(year):
        print(year, "is a leap year")
    else:
        print(year, "is not a leap year")

Output:

Tutorials Class - Output Window

2024 is a leap year
1900 is not a leap year
2000 is a leap year
2023 is not a leap year

How it works

  • 2024 is divisible by 4 and not by 100, so it is a leap year.
  • 1900 is divisible by 100 but not by 400, so it is not a leap year.
  • 2000 is divisible by 400, so it is a leap year.
  • 2023 is not divisible by 4.

Python calculator program using functions

Description: Write a simple calculator in Python using a function. It should support +, -, * and /.

Rules and hints:

  • Write one function that takes two numbers and an operator.
  • Check for division by zero.
  • Return a message for a wrong operator.

Python calculator program

def calculate(a, b, op):
    if op == "+":
        return a + b
    elif op == "-":
        return a - b
    elif op == "*":
        return a * b
    elif op == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    else:
        return "Invalid operator"

print(calculate(10, 5, "+"))
print(calculate(10, 5, "-"))
print(calculate(10, 5, "*"))
print(calculate(10, 5, "/"))
print(calculate(10, 0, "/"))

Output:

Tutorials Class - Output Window

15
5
50
2.0
Cannot divide by zero

How it works

  • The function checks the operator with if and elif and returns the answer.
  • A division by zero would crash the program, so we check b == 0 first.
  • You can read the numbers and the operator with input() to make it interactive.

Related: Python Functions.

Python program to print multiplication table

Description: Write a Python program to print the multiplication table of a number.

Rules and hints:

  • Use a for loop with range(1, 11).
  • Print each line in the form 7 x 1 = 7.

Python program for multiplication table

num = 7

for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")

Output:

Tutorials Class - Output Window

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

How it works

  • range(1, 11) gives the numbers 1 to 10. The end value 11 is not included.
  • In each round the f-string puts the values of num, i and the product in the line.

Learn more in Python for loop.

Python program to find factorial of a number

Description: Write a Python program to find the factorial of a number using a loop.

Rules and hints:

  • Factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
  • Start with 1 and multiply by each number.

Python program for factorial using a loop

num = 5
factorial = 1

for i in range(1, num + 1):
    factorial = factorial * i

print("Factorial of", num, "is", factorial)

Output:

Tutorials Class - Output Window

Factorial of 5 is 120

How it works

  • factorial starts with 1.
  • The loop multiplies it with 1, 2, 3, 4 and 5 one by one: 1, 2, 6, 24, 120.
  • For 0, the loop does not run, and the answer stays 1, which is correct.

You can also solve it with a function that calls itself. See Python Functions (recursion).

Python program to print Fibonacci series

Description: Write a Python program to print the first 10 numbers of the Fibonacci series.

Rules and hints:

  • Each number is the sum of the two numbers before it.
  • The series starts with 0 and 1.

Python program for Fibonacci series

a, b = 0, 1

for _ in range(10):
    print(a, end=" ")
    a, b = b, a + b

Output:

Tutorials Class - Output Window

0 1 1 2 3 5 8 13 21 34

How it works

  • a and b hold two neighbour numbers of the series.
  • print(a, end=" ") prints on the same line with a space.
  • a, b = b, a + b moves to the next pair at once.
  • The loop variable _ means we do not use its value.

Python program to check prime number

Description: Write a Python program to check whether a number is prime.

Rules and hints:

  • A prime number is greater than 1 and has no divisor other than 1 and itself.
  • You only need to test divisors up to the square root of the number.

Python program to check a prime number

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

for n in (2, 15, 17, 1):
    if is_prime(n):
        print(n, "is prime")
    else:
        print(n, "is not prime")

Output:

Tutorials Class - Output Window

2 is prime
15 is not prime
17 is prime
1 is not prime

How it works

  • Numbers below 2 are not prime.
  • For 15 the loop tests 2 and 3. Since 15 % 3 == 0, it returns False.
  • For 17 the loop tests 2, 3 and 4. None divides it, so it is prime.
  • As soon as one divisor is found, return False ends the function early.

Python program to print star pattern (right triangle)

Description: Write a Python program to print a right angled triangle pattern of stars with 5 rows.

Rules and hints:

  • Row 1 has one star, row 2 has two stars, and so on.
  • You can repeat a string with *, like "*" * 3.

Python star pattern program

rows = 5

for i in range(1, rows + 1):
    print("*" * i)

Output:

Tutorials Class - Output Window

*
**
***
****
*****

How it works

  • In round i we print the star i times.
  • print() adds a new line after each row.

Related: Python Strings.

Python program to check palindrome string

Description: Write a Python program to check whether a string is a palindrome.

Rules and hints:

  • A palindrome reads the same from both sides, like madam.
  • Ignore upper and lower case.

Python program to check a palindrome

def is_palindrome(text):
    text = text.lower()
    return text == text[::-1]

for word in ("madam", "Level", "python"):
    if is_palindrome(word):
        print(word, "is a palindrome")
    else:
        print(word, "is not a palindrome")

Output:

Tutorials Class - Output Window

madam is a palindrome
Level is a palindrome
python is not a palindrome

How it works

  • lower() changes the text to lowercase, so “Level” becomes “level”.
  • text[::-1] is the reversed string.
  • If the text equals its reverse, it is a palindrome.

Read about slicing in Python Strings.

Python program to count vowels in a string

Description: Write a Python program to count the number of vowels in a string.

Rules and hints:

  • Vowels are a, e, i, o and u.
  • Change the text to lowercase first, so capital letters are counted too.

Python program to count vowels

text = "Tutorials Class"
vowels = "aeiou"
count = 0

for ch in text.lower():
    if ch in vowels:
        count += 1

print("Number of vowels:", count)

Output:

Tutorials Class - Output Window

Number of vowels: 5

How it works

  • The loop checks each character of the text.
  • ch in vowels is True when the character is one of a, e, i, o, u.
  • The vowels in “Tutorials Class” are u, o, i, a and a, so the count is 5.

Python program to reverse a string

Description: Write a Python program to reverse a string in three different ways.

Rules and hints:

  • Strings are immutable, so you create a new string.

Python program to reverse a string

text = "Python"

# 1. slicing
print(text[::-1])

# 2. reversed() and join()
print("".join(reversed(text)))

# 3. loop
result = ""
for ch in text:
    result = ch + result
print(result)

Output:

Tutorials Class - Output Window

nohtyP
nohtyP
nohtyP

How it works

  • Slicing with step -1 goes through the string from the end.
  • reversed() gives the characters in reverse order, and join() makes a string again.
  • In the loop, every new character is added to the front of result.

Related: join() function.

Python program to find largest and smallest number in a list

Description: Write a Python program to find the largest and the smallest number in a list.

Rules and hints:

  • First use the built-in max() and min() functions.
  • Then do it with a loop, without these functions.

Python program to find the largest and smallest number in a list

numbers = [45, 12, 89, 3, 67]

print("Largest:", max(numbers))
print("Smallest:", min(numbers))

largest = smallest = numbers[0]
for n in numbers:
    if n > largest:
        largest = n
    if n < smallest:
        smallest = n

print("Loop result:", largest, smallest)

Output:

Tutorials Class - Output Window

Largest: 89
Smallest: 3
Loop result: 89 3

How it works

  • max() and min() check the whole list for you.
  • In the loop we start with the first item as both largest and smallest, and update them when a bigger or smaller item comes.

Learn more in Python Lists.

Python program to remove duplicates from a list

Description: Write a Python program to remove the duplicate items from a list.

Rules and hints:

  • A set keeps only unique values, but it does not keep the order.
  • dict.fromkeys() keeps the order of the first appearance.

Python program to remove duplicates from a list

items = [1, 2, 2, 3, 4, 4, 5]

unique_sorted = sorted(set(items))
unique_ordered = list(dict.fromkeys(items))

print(unique_sorted)
print(unique_ordered)

Output:

Tutorials Class - Output Window

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

How it works

  • set(items) removes the duplicates, and sorted() makes a sorted list of it.
  • A dictionary cannot have duplicate keys, and in Python 3.7+ it keeps the insertion order. So dict.fromkeys(items) followed by list() keeps the first order.

Related: Python Sets and Python Dictionary.

Python program to find the sum of digits of a number

Description: Write a Python program to find the sum of the digits of a number.

Rules and hints:

  • Use % 10 to get the last digit.
  • Use // 10 to remove the last digit.

Python program for the sum of digits

num = 1234
total = 0

while num > 0:
    total += num % 10
    num = num // 10

print("Sum of digits:", total)

Output:

Tutorials Class - Output Window

Sum of digits: 10

How it works

  • 1234 % 10 is 4, and then 1234 // 10 is 123.
  • The loop continues with 123, 12 and 1, adding 3, 2 and 1.
  • So the total is 4 + 3 + 2 + 1 = 10. The loop stops when the number becomes 0.

Learn more in Python While Loop.

Python program to find the sum of natural numbers using recursion

Description: Write a Python program to find the sum of the first n natural numbers using recursion.

Rules and hints:

  • A recursive function calls itself.
  • Every recursive function needs a stopping (base) case.

Python program for the sum of natural numbers using recursion

def sum_to(n):
    if n == 0:
        return 0          # base case
    return n + sum_to(n - 1)

print(sum_to(5))
print(sum_to(10))

Output:

Tutorials Class - Output Window

15
55

How it works

  • sum_to(5) returns 5 + sum_to(4), and so on, down to sum_to(0) which returns 0.
  • The results come back as 0, 1, 3, 6, 10 and 15.
  • Without the base case the function would never stop and Python would raise a RecursionError.

See the Recursion section of Python Functions.