Check a prime number

Python Practice › Basic Programs › Program 28

Check a prime number

MediumBasic Programs · 28 of 40

Write a Python program to check whether a number is prime (greater than 1 and divisible only by 1 and itself).

Input
29, 33, 1, 97
Output
29 True
33 False
1 False
97 True

Approach

  1. Numbers below 2 are not prime.
  2. Try dividing by every number from 2 up to the square root; any exact division means not prime.

Solution

Python
def is_prime(n):    if n < 2:        return False    for d in range(2, int(n ** 0.5) + 1):        if n % d == 0:            return False    return True for n in [29, 33, 1, 97]:    print(n, is_prime(n))
Output
29 True
33 False
1 False
97 True

Line by line

Lines 2-3

0, 1 and negative numbers are not prime.

Line 4

Checking up to √n is enough: if n had a factor larger than √n, it would also have one smaller than √n.

Lines 5-6

Return False as soon as a divisor is found.

Line 7

No divisor was found, so the number is prime.

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

Check an Armstrong number

Python Practice › Basic Programs › Program 19

Check an Armstrong number

MediumBasic Programs · 19 of 40

Write a Python program to check whether a number is an Armstrong number: the sum of its digits, each raised to the power of the number of digits, equals the number (153 = 1³ + 5³ + 3³).

Input
153, 370, 123, 9474
Output
153 True
370 True
123 False
9474 True

Approach

  1. Count the digits.
  2. Raise each digit to that power and add them up.
  3. Compare the sum with the original number.

Solution

Python
def is_armstrong(n):    digits = str(n)    power = len(digits)    total = sum(int(d) ** power for d in digits)    return total == n for n in [153, 370, 123, 9474]:    print(n, is_armstrong(n))
Output
153 True
370 True
123 False
9474 True

Line by line

Line 2

Turning the number into a string makes it easy to loop over its digits.

Line 3

The power is the number of digits: 3 for 153, 4 for 9474.

Line 4

The generator expression converts each digit back to int, raises it to power and sum() adds them.

Line 5

The function returns True only when the sum equals the number.

Learn the concept

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

More basic programs

← All 40 Basic Programs