Check for an anagram

Python Practice › Basic Programs › Program 30

Check for an anagram

MediumBasic Programs · 30 of 40

Write a Python program to check whether two words are anagrams: one is a rearrangement of all the letters of the other.

Input
"listen" and "silent", "apple" and "paple", "hello" and "world"
Output
True
True
False

Approach

  1. Ignore case and spaces.
  2. Two words are anagrams if their sorted letters are the same.

Solution 1: sorting

Python
def is_anagram(a, b):    clean_a = a.replace(" ", "").lower()    clean_b = b.replace(" ", "").lower()    return sorted(clean_a) == sorted(clean_b) print(is_anagram("listen", "silent"))print(is_anagram("Dormitory", "dirty room"))print(is_anagram("hello", "world"))
Output
True
True
False

Line by line

Lines 2-3

Remove spaces and lower-case both words so “Dormitory” and “dirty room” compare fairly.

Line 4

sorted() turns each word into a sorted list of letters; equal lists mean the same letters.

Solution 2: Counter

Python
from collections import Counterprint(Counter("apple") == Counter("paple"), Counter("abc") == Counter("abd"))
Output
True False

Line by line

Line 2

Counter counts each letter; anagrams have identical counts.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Check a leap year

Python Practice › Basic Programs › Program 29

Check a leap year

EasyBasic Programs · 29 of 40

Write a Python program to check whether a year is a leap year: divisible by 4, except century years, which must be divisible by 400.

Input
1900, 2000, 2024, 2026
Output
1900 not leap
2000 leap
2024 leap
2026 not leap

Approach

  1. Combine the rules with and / or.

Solution 1: the rules

Python
for year in [1900, 2000, 2024, 2026]:    leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0    print(year, "leap" if leap else "not leap")
Output
1900 not leap
2000 leap
2024 leap
2026 not leap

Line by line

Line 2

Divisible by 4 but not by 100, or divisible by 400.

Solution 2: calendar module

Python
import calendarprint([y for y in [1900, 2000, 2024, 2026] if calendar.isleap(y)])
Output
[2000, 2024]

Line by line

Line 2

calendar.isleap() implements the same rules.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Compound interest

Python Practice › Basic Programs › Program 27

Compound interest

EasyBasic Programs · 27 of 40

Write a Python program to calculate compound interest. Amount = P × (1 + R/100)ᵀ and interest = amount − P.

Input
P = 10000, R = 8, T = 5 (compounded yearly)
Output
Amount: 14693.28
Compound interest: 4693.28

Approach

  1. Compute the final amount with the formula.
  2. Subtract the principal to get the interest.

Solution

Python
principal = 10000rate = 8years = 5 amount = principal * (1 + rate / 100) ** yearsinterest = amount - principalprint("Amount:", round(amount, 2))print("Compound interest:", round(interest, 2))
Output
Amount: 14693.28
Compound interest: 4693.28

Line by line

Line 5

(1 + rate / 100) is the growth factor per year; ** years applies it for every year.

Lines 7-8

round(..., 2) shows rupees and paise.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Check a palindrome number

Python Practice › Basic Programs › Program 26

Check a palindrome number

EasyBasic Programs · 26 of 40

Write a Python program to check whether a number is a palindrome (reads the same backwards, like 12321).

Input
12321, 12345
Output
12321 is a palindrome
12345 is not a palindrome

Approach

  1. Reverse the digits and compare with the original.

Solution

Python
def is_palindrome(n):    text = str(n)    return text == text[::-1] for n in [12321, 12345]:    print(n, "is a palindrome" if is_palindrome(n) else "is not a palindrome")
Output
12321 is a palindrome
12345 is not a palindrome

Line by line

Lines 2-3

Comparing the string with its reverse gives True or False directly.

Line 6

A conditional expression chooses the message.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Fibonacci series up to 50

Python Practice › Basic Programs › Program 25

Fibonacci series up to 50

EasyBasic Programs · 25 of 40

Write a Python program to print the Fibonacci series between 0 and 50. Each number is the sum of the two before it.

Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Approach

  1. Start with a = 0 and b = 1.
  2. Print a, then move forward with a, b = b, a + b until a passes 50.

Solution

Python
a, b = 0, 1series = []while a <= 50:    series.append(a)    a, b = b, a + bprint(series)
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Line by line

Line 1

The series starts with 0 and 1.

Line 3

The loop stops as soon as the next number would be above 50.

Line 5

Both variables update at once: the new a is the old b, and the new b is the sum of the old pair.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Reverse a number

Python Practice › Basic Programs › Program 24

Reverse a number

EasyBasic Programs · 24 of 40

Write a Python program to reverse the digits of a number.

Input
12345
Output
54321

Approach

  1. Take the last digit with % 10 and remove it with // 10.
  2. Build the reversed number digit by digit.

Solution 1: arithmetic

Python
n = 12345reversed_n = 0while n > 0:    digit = n % 10    reversed_n = reversed_n * 10 + digit    n //= 10print(reversed_n)
Output
54321

Line by line

Line 4

n % 10 is the last digit (5 first).

Line 5

Shifting the result one place left (* 10) and adding the digit appends it.

Line 6

//= 10 removes the last digit; the loop ends when n reaches 0.

Solution 2: string slicing

Python
n = 12345print(int(str(n)[::-1]))
Output
54321

Line by line

Line 2

Convert to a string, reverse it with [::-1] and convert back to int.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Factorial of a number

Python Practice › Basic Programs › Program 23

Factorial of a number

EasyBasic Programs · 23 of 40

Write a Python program to find the factorial of a number. n! = 1 × 2 × … × n, and 0! = 1.

Input
n = 6
Output
6! = 720

Approach

  1. Start with 1 and multiply by every number from 2 to n.

Solution 1: loop

Python
n = 6factorial = 1for i in range(2, n + 1):    factorial *= iprint(f"{n}! = {factorial}")
Output
6! = 720

Line by line

Line 2

Start at 1, the identity for multiplication (and the value of 0!).

Line 3

range(2, n + 1) gives 2, 3, 4, 5, 6; the end value is excluded, so add 1.

Line 4

*= multiplies the running result by each number.

Solution 2: math.factorial

Python
import mathprint(math.factorial(6), math.factorial(0))
Output
720 1

Line by line

Line 2

The standard library already has an efficient factorial function.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Days between two dates

Python Practice › Basic Programs › Program 22

Days between two dates

EasyBasic Programs · 22 of 40

Write a Python program to calculate the number of days between two dates.

Input
(2023, 1, 5) and (2023, 1, 22)
Output
17 days

Approach

  1. Create two date objects.
  2. Subtract them to get a timedelta and read its .days.

Solution

Python
from datetime import date start = date(2023, 1, 5)end = date(2023, 1, 22)gap = end - startprint(gap.days, "days")
Output
17 days

Line by line

Line 5

Subtracting dates gives a timedelta object.

Line 6

.days is the whole number of days between them.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Print the current date in a format

Python Practice › Basic Programs › Program 21

Print the current date in a format

EasyBasic Programs · 21 of 40

Write a Python program to print the current date in the format “2023 Jan 05” (year, short month name, day) using the datetime module.

Output
2026 Nov 02

Approach

  1. Get today’s date with date.today().
  2. Format it with strftime("%Y %b %d").

Solution

Python
from datetime import date today = date.today()print(today.strftime("%Y %b %d"))
Output
2026 Nov 02

Line by line

Line 3

date.today() reads the date from your computer’s clock.

Line 4

%Y is the 4-digit year, %b the short month name and %d the 2-digit day.

Note

The output shows the date on which this page was built. Press Try it and Run to see today’s date.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Simple interest

Python Practice › Basic Programs › Program 20

Simple interest

EasyBasic Programs · 20 of 40

Write a Python program to calculate simple interest. Simple interest = P × R × T / 100, where P is the principal, R the yearly rate in percent and T the time in years.

Input
P = 10000, R = 6.5, T = 3
Output
Simple interest: 1950.0
Total amount: 11950.0

Approach

  1. Apply the formula.
  2. Add the interest to the principal for the total amount.

Solution

Python
principal = 10000rate = 6.5years = 3 interest = principal * rate * years / 100amount = principal + interestprint("Simple interest:", interest)print("Total amount:", amount)
Output
Simple interest: 1950.0
Total amount: 11950.0

Line by line

Line 5

Dividing by 100 converts the percentage rate into a fraction.

Line 6

The amount repaid is the principal plus the interest.

Note

The original version of this exercise listed the formula as P + (P/r)*t, which is not the simple interest formula. The correct formula is P × R × T / 100.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs