Add two numbers
# taking user input
a = input("First number: ")
b = input("Second number: ")
# converting input to float and adding
res = float(a) + float(b)
print(res)
Factorial of a Number - Python
Given an integer n, the task is to compute its factorial, i.e., the product of
all positive integers from 1 to n. Factorial is represented as n! and is
commonly used in mathematics, permutations and combinatorics. For
Example:
Input: n = 6
Output: 720
Explanation: 6! = 6 × 5 × 4 × 3 × 2 × 1 = 720
Let's explore different methods to find the factorial of a number in Python.
Using [Link]()
This method computes the factorial using Python’s built-
in factorial() function, which performs the entire calculation internally
without requiring loops or recursion in user code.
import math
n = 6
print([Link](n))
Output
720
Using NumPy’s [Link]()
NumPy performs multiplication through optimized C-level operations. It
computes the factorial by multiplying all numbers from 1 to n in a single
vectorized step using [Link]().
import numpy as np
n = 6
print([Link](range(1, n+1)))
Output
720
Explanation:
range(1, n+1) generates numbers from 1 through n.
[Link](...) multiplies all values in the sequence.
Using an Iterative For Loop
This method calculates factorial by manually multiplying the numbers from
1 to n inside a for loop.
n = 6
f = 1
for i in range(1, n+1):
f *= i
print(f)
Output
720
Explanation:
f = 1 starts with an initial multiplication value.
f *= i multiplies f with each number i from 1 to n.
Produces the factorial after the loop completes.
Using a Recursive Function
This approach follows the mathematical definition of factorial by
repeatedly calling the function with decreasing values until reaching the
base case.
def fact(n):
return 1 if n <= 1 else n * fact(n-1)
print(fact(6))
Output
720
Python Program for Simple Interest
The task of calculating Simple Interest in Python involves taking inputs for
principal amount, time period in years, and rate of interest per annum,
applying the Simple Interest formula and displaying the result. For
example, if p = 1000, t = 2 (years), and r = 5%, the Simple Interest is
calculated using the formula and resulting in Simple Interest = 100.0.
Simple interest formula :
Simple Interest = (P x T x R)/100
Where:
P is the Principal amount
T is the Time period (in years)
R is the Rate of interest per annum
Using function
Defining a function to calculate Simple Interest enhances readability and
reusability. It is ideal when the calculation needs to be performed multiple
times with different values. By calling the function with desired inputs, we
get results without duplicating code, making the program cleaner and
easier to maintain.
def fun(p, t, r):
return (p * t * r) / 100
p, t, r = 8, 6, 8
res = fun(p, t, r)
print(res)
Output
3.84
Explanation: In this example we defines a function called fun that
calculates simple interest based on three input values: principal (p), time
(t) in years, and rate of interest (r) per annum. The function returns the
result of the simple interest formula.
Using lambda function
lambda function is useful for quick, single-line calculations like Simple
Interest without defining a separate function. It helps in making the code
compact and concise, but may reduce readability if the logic becomes
complex.
si = lambda p, t, r: (p * t * r) / 100
p, t, r = 8, 6, 8
res = si(p, t, r)
print(res)
Output
3.84
Explanation: lambda p, t, r: (p * t * r) / 100 takes three parameters: p
(principal), t (time in years) and r (rate of interest per annum). It
calculates Simple Interest and returns the result.
Using list comprehension
List comprehension allows us to generate lists in a single line of code
using a simple syntax. While it is generally used to build lists from existing
iterables, it can sometimes be creatively used for quick calculations
though this is more of a trick than a recommended practice.
p, t, r = 8, 6, 8
si = [p * t * r / 100][0]
print(si)
Output
3.84
Python Program to Check Armstrong Number
Given a number x, determine whether given number is Armstrong number
or not. An Armstrong number is a number that is equal to the sum of its
own digits each raised to the power of the number of digits.
For example:
153 = 1³ + 5³ + 3³ = 153 (Armstrong number)
120 ≠ 1³ + 2³ + 0³ = 9 (Not an Armstrong number)
Let’s explore different methods to check Armstrong numbers one by one.
Mathematical Method (Most Optimal)
This is the fastest and most efficient way to check an Armstrong number.
It uses integer arithmetic only, avoiding any string conversion overhead.
num = int(input("Enter a number: "))
n = num
power = len(str(num))
total = 0
while n > 0:
digit = n % 10
total += digit ** power
n //= 10
if total == num:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
Output
153 is an Armstrong number
Explanation:
len(str(num)) gives the number of digits.
Each digit is extracted using % 10.
The digit is raised to the power of total digits.
The loop adds all powered digits and checks if the sum equals the
original number.
String Conversion Method
This version is simpler and more readable. It leverages Python’s built-in
features like sum() and list comprehensions.
Converts the number to a string to easily loop over each digit.
Converts each digit back to an integer for calculation.
Uses sum() for a concise and elegant approach.
num = 153
num2 = str(num)
n = len(num2)
sum1 = 0
for digit in num2:
sum1 += int(digit) ** n
if sum1 == num:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
Output
153 is an Armstrong number
Using map() and lambda (Functional Style)
This is a compact and one-liner-friendly approach, often used by those
who prefer functional programming.
map() applies the lambda function to each digit in the number.
Each digit is raised to the required power.
The sum is compared with the original number. n = 153
s = n
b = len(str(n))
sum1 = 0
while n != 0:
r = n % 10
sum1 = sum1 + (r ** b)
n = n // 10
if s == sum1:
print(s, "is an Armstrong number")
else:
print(s, "is not an Armstrong number")
Output
153 is an Armstrong number
Please refer complete article on Program for Armstrong Numbers for more
details!
Recursive Method (Educational, Not Practical)
This approach uses recursion instead of loops. It’s more of a learning
exercise than a practical solution.
num = int(input("Enter a number: "))
power = len(str(num))
def armstrong_sum(n):
if n == 0:
return 0
return (n % 10) ** power + armstrong_sum(n // 10)
if armstrong_sum(num) == num:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
Output
1634 is an Armstrong number.
Check Prime Number in Python
Given a positive integer N, the task is to write a Python program to check
if the number is Prime or not in Python.
For example, given a number 29, it has no divisors other than 1 and 29
itself. Hence, it is a prime number.
Note: Negative numbers (e.g. -13) are not considered prime number.
Let’s look at the methods below to check for a prime number:
Using flag variable
We can check if a number is prime or not by traversing all the numbers
from 2 to sqrt(n)+1 and checking if n is divisible by any of those numbers.
Note: We iterate only up to the square root of n because if n has any
divisor greater than its square root, there must also be a corresponding
divisor smaller than the square root. So, checking beyond sqrt(n) is
unnecessary and would only waste computation.
n = 11
if n <= 1:
print(False)
else:
is_prime = True # Flag variable
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
is_prime = False
break
print(is_prime)
Output
True
Explanation:
Check if n <= 1, if true, it's not prime.
Loop from 2 to the square root of n, if n % i == 0, it's not prime. If no
divisors found, n is prime.
Using [Link]() method
In the sympy module, we can test whether a given number 'n' is prime or
not using [Link]() function. For n < 2 64 the answer is definitive;
larger n values have a small probability of actually being pseudoprimes.
Before using sympy module, we need to install it using this command:
pip install sympy
from sympy import *
g1 = isprime(13)
print(g1)
Output
True
Explanation:
isprime() function from the SymPy library checks if a number is prime
or not.
It prints False for 30, True for 13 and True for 2 because 30 is not
prime, while 13 and 2 are prime numbers.
Using Sieve of Eratosthenes Algorithm
Although the Sieve of Eratosthenes is primarily used to find all prime
numbers up to a given number n, it can also be used to check whether a
specific number is prime or not.
def is_prime(n):
if n < 2:
return False
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(n**0.5) + 1):
if sieve[i]:
for j in range(i * i, n + 1, i):
sieve[j] = False
return sieve[n]
num = 31
print(is_prime(num))
Output
True
Explanation:
Create a Boolean list "sieve" where each index represents a number.
Mark '0' and '1' as "False" since they are not prime.
For each number 'i', mark all its multiples as non-prime.
After completing the sieve, check if sieve[n] is True (prime) or False
(not prime).
Using Recursion
We can also find if the number is prime or not using recursion by checking
for some base cases and recursively call for a number less than the
current one.
from math import sqrt
def Prime(n, i):
if i == 1 or i == 2:
return True
if n % i == 0:
return False
return Prime(n, i - 1)
n = 13
i = int(sqrt(n) + 1)
print(Prime(n, i))
Output
True
ow to Check if a Given Number is Fibonacci
number - Python
Fibonacci numbers are part of a famous sequence where each number is
the sum of the two preceding ones, i.e. F(n) = F(n-1) + F(n-2). The
sequence starts as:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Notice that every number is equal to the sum of its previous 2 numbers.
In this article, we will learn how to identify if a given number belongs to the
Fibonacci series or not.
Examples :
Input: 8
Output: Yes
Input: 31
Output: No
Fibonacci Number Check Using a Mathematical
Property
A number n is a Fibonacci number if and only if one or both of (5*n² + 4)
or (5*n² – 4) is a perfect square.
The above mathematical expression is derived from the closed-form
expression of Fibonacci numbers (Binet’s Formula) and some number
theory. It’s fast and doesn’t require generating the Fibonacci sequence.
Let's look at the code implementation in Python:
import math
def is_perfect_sq(x):
s = int([Link](x))
return s * s == x
def is_fibonacci(n):
return is_perfect_sq(5 * n * n + 4) or is_perfect_sq(5 *
n * n - 4)
for i in range(1, 7):
if is_fibonacci(i):
print(f"{i} is a Fibonacci Number")
else:
print(f"{i} is not a Fibonacci Number")
Output
1 is a Fibonacci Number
2 is a Fibonacci Number
3 is a Fibonacci Number
4 is not a Fibonacci Number
5 is a Fibonacci Number
6 is not a Fibonacci Number