Python Programs
1.Hello
World Program
Source
Code
#
This program prints Hello, world!
print('Hello, world!')
Output:-
Hello,
world!
In this program, we have
used the built-in print() function to print the
string Hello,
world! on
our screen. String is a sequence of characters. In Python, strings are enclosed
inside single quotes, double quotes or triple quotes (''', """).
Python Program to Add Two Numbers
Source
Code
# This program adds two numbers provided by the user
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Output:-
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
Explanation
In this program, we
asked user to enter two numbers and this program displays the sum of tow
numbers entered by user. We use the built-in function input()
to take the input. input()
returns a string, so we convert it into
number using the float()
function.
We add the two
numbers using the +
arithmetic operator. Changing this operator,
we can subtract (-), multiply (*), divide (/), floor divide (//) or find the
remainder (%) of two numbers. Find out more aboutarithmetic operators and input in Python.
Alternative to this,
we can perform this addition in a single statement without using any variables
as follows.
print('The sum is %.1f' %(float(input('Enter first number: '))+float(input('Enter second number: '))))
Although this program
uses no variable (memory efficient), it is not quite readable. Some people will
have difficulty understanding it. It is better to write clear codes. So, there
is always a compromise between clarity and efficiency. We need to strike a
balance.
Python Program to Find the Square Root
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python Program to calculate the square root
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Output:-
Enter a number: 8
The square root of 8.000 is 2.828
In this program, we
ask the user for a number and find the square root using the **
exponent operator. This program works for all
positive real numbers. But for negative or complex numbers, it can be done as
follows.
# Find square root of real or complex numbers
# Import the complex math module
import cmath
num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
Output:-
Enter a number: 1+2j
The square root of (1+2j) is 1.272+0.786j
In this program, we
use the sqrt()
function in the cmath
(complex math) module. Notice that we have
used the eval()
function instead of float()
to convert complex number as well. Also
notice the way in which the output is formatted. Look here for more about string formatting in Python.
Python Program to Calculate the Area of a
Triangle
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python Program to find the area of triangle
# Three sides of the triangle a, b and c are provided by the user
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Output:-
Enter first side: 5
Enter second side: 6
Enter third side: 7
The area of the triangle is 14.70
In this program, we
asked users to enter the length of three sides of a triangle. We used the Heron's Formula to calculate
the semi-perimeter and hence the area of the triangle.
Python Program to Solve Quadratic Equation
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Solve the quadratic equation ax**2 + bx + c = 0
# Coeffients a, b and c are provided by the user
# import complex math module
import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
Output:-
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
In this program, we
ask the user for the coefficients of the quadratic equation. We have imported
thecmath
module to perform complex square root. First we
calculate the discriminant and then find the two solutions of the quadratic
equation.
Python Program to Swap Two Variables
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python program to swap two variables provided by the user
x = input('Enter value of x: ')
y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output:-
Enter value of x: 5
Enter value of y: 10
The value of x after swapping: 10
The value of y after swapping: 5
In this program, we
use the temp variable to temporarily hold the value
of x. We then put the
value ofy in x and later temp in y.
In this way, the values get exchanged.
Python
Program to Swap Variables Without Temporary Variable
In python
programming, there is a simple construct to swap variables. The following code
does the same as above but without the use of any temporary variable.
x,y = y,x
If the variables are
both numbers, we can use arithmetic operations to do the same. It might not
look intuitive at the first sight. But if you think about it, its pretty easy
to figure it out.Here are a few example
Addition and Subtraction
x = x + y
y = x - y
x = x - y
Multiplication and Division
x = x * y
y = x / y
x = x / y
XOR swap
This algorithm works
for integers only
x = x ^ y
y = x ^ y
x = x ^ y
Python Program to Generate a Random Number
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Program to generate a random number between 0 and 9
# import the random module
import random
print(random.randint(0,9))
Output:-
5
In this program, we
use the randint()
function inside the random module. Note that, we may
get different output because this program generates random number in range
0 and 9. The syntax of this function is:
random.randint(a,b)
This returns a number N in the inclusive range [a,b]
, meaning a <= N <= b
, where the endpoints
are included in the range.
Python Program to Convert Kilometers to
Miles
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Program to convert kilometers into miles
# Input is provided by the user in kilometers
# take input from the user
kilometers = float(input('How many kilometers?: '))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))
Output:-
How many kilometers?: 5.5
5.500 kilometers is equal to 3.418 miles
Explanation
In this program, we
use the ask the user for kilometers and convert it to miles by multiplying it
with the conversion factor. With a slight modification, we can convert miles to
kilometers. We ask for miles and use the following formula to convert it into
kilometers.
kilometers = miles / conv_fac
Python Program to Convert Celsius To
Fahrenheit
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python Program to convert temperature in celsius to fahrenheit
# Input is provided by the user in degree celsius
# take input from the user
celsius = float(input('Enter degree Celsius: '))
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
Output:-
Enter degree Celsius: 37.5
37.5 degree Celsius is equal to 99.5 degree Fahrenheit
In this program, we
ask the user for temperature in degree Celsius and convert it into degree
Fahrenheit. They are related by the formula celsius * 1.8 =
fahrenheit - 32
. With a simple modification to this program, we can
convert Fahrenheit into Celsius. We ask the user for temperature in Fahrenheit
and use the following formula to convert it into Celsius.
celsius = (fahrenheit - 32) / 1.8
Python Program to Check if a Number is
Positive, Negative or Zero
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# In this python program, user enters a number and checked if the number is positive or negative or zero
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Here, we have used
the if...elif...else
statement. We can do the same thing using
nested if
statements as
follows.
# This time use nested if to solve the problem
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output 1:-
Enter a number: 2
Positive number
Output 2:-
Enter a number: 0
Zero
A number is positive
if it is greater than zero. We check this in the expression of if
. If it is False
, the number will
either be zero or negative. This is also tested in subsequent expression.
Python Program to check if a Number is odd
or Even
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python program to check if the input number is odd or even.
# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Output 1:-
Enter a number: 43
43 is Odd
Output 2:-
Enter a number: 18
18 is Even
In this program, we
ask the user for the input and check if the number is odd or even. A number is
even if it is perfectly divisible by 2. When the number is divided by 2, we use
the remainder operator%
to compute the
remainder. If the remainder is not zero, the number is odd.
Python Program to Check Leap Year
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python program to check if the input year is a leap year or not
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output 1:-
Enter a year: 2000
2000 is a leap year
Output 2:-
Enter a year: 1775
1775 is not a leap year
In this program, we
ask the user to input a year and check if it is a leap year or not. Leap years
are those divisible by 4. Except those that are divisible by 100 but not by
400. Thus 1900 is not a leap year as it is divisible by 100. But 2000 is a leap
year because it if divisible by 400 as well.
Python Program to Find the Largest Among
Three Numbers
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python program to find the largest number among the three input numbers
# take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
Output 1:-
Enter first number: 10
Enter second number: 12
Enter third number: 14
The largest number is 14.0
Output 2:-
Enter first number: -1
Enter second number: 0
Enter third number: -3
The largest number is 0.0
In this program, we
ask the user to input three numbers. We use the if...elif...else
ladder to find the largest among the three
and display it.
Python Program to Check Prime Number
To understand this example, you should have knowledge of following Python programming topics:
A positive integer
greater than 1 which has no other factors except 1 and the number itself is
called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have
any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6
.
Source
Code
# Python program to check if the input number is prime or not
# take input from the user
num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
Output 1:-
Enter a number: 407
407 is not a prime number
11 times 37 is 407
Output 2:-
Enter a number: 853
853 is a prime number
In this program, user
is asked to enter a number and this program check whether that number is prime
or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only
proceed if thenum is greater than 1. We
check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the
number is not prime. Else the number is prime.
We can decrease the
range of numbers where we look for factors. In the above program, our search
range is from 2 to num - 1. We could have used the range, [2, num / 2] or [2, num ** 0.5]. The later range is based on the fact
that a composite number must have a factor less than square root of that
number. Otherwise the number is prime.
Python Program to print all Prime Numbers
in an Interval
To understand this example, you should have knowledge of following Python programming topics:
A positive integer
greater than 1 which has no other factors except 1 and the number itself is
called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have
any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6
. We ask the user for
a range and display all the primes in that interval.
Source
Code
# Python program to ask the user for a range and display all the prime numbers in that interval
# take input from the user
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Output:-
Enter lower range: 900
Enter upper range: 1000
907
911
919
929
937
941
947
953
967
971
977
983
991
997
Python Program to Find the Factorial of a
Number
To understand this example, you should have knowledge of following Python programming topics:
The factorial of a
number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not
defined for negative numbers and the factorial of zero is one, 0! = 1.
Source
Code
# Python program to find the factorial of a number provided by the user.
# take input from the user
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output 1:-
Enter a number: -2
Sorry, factorial does not exist for negative numbers
Output 2:-
Enter a number: 7
The factorial of 7 is 5040
Here, we take input
from the user and check if the number is negative, zero or positive usingif...elif...else
statement. If the number is positive, we use for
loop and range()
function to calculate the factorial.
Python Program to Display the
multiplication Table
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python program to find the multiplication table (from 1 to 10) of a number input by the user
# take input from the user
num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1,11):
print(num,'x',i,'=',num*i)
Output:-
Display multiplication table of? 12
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
Here, we ask the user
for a number and display the multiplication table upto 10. We use for
loop along with the range()
function to iterate 10 times.
Python Program to Print the Fibonacci
sequence
To understand this example, you should have knowledge of following Python programming topics:
A Fibonacci sequence
is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0
and 1. All other terms are obtained by adding the preceding two terms. This
means to say the nth term is the sum of (n-1)th and (n-2)th term.
Source
Code
# Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# take input from the user
nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
Output:-
How many terms? 10
Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Here, we ask the user
for the number of terms in the sequence. We initialize the first term to 0 and
the second term to 1. If the number of terms is more than 2, we use a while
loop to find the next term in the sequence by
adding the preceding two terms. We then interchange the variables (update it)
and continue on with the process.
Python Program to Check Armstrong Number
To understand this example, you should have knowledge of following Python programming topics:
An Armstrong number,
also known as narcissistic number, is a number that is equal to the sum of the
cubes of its own digits. For example, 370 is an Armstrong number since 370 =
3*3*3 + 7*7*7 + 0*0*0.
Source
Code
# Python program to check if the number provided by the user is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialise sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output 1:-
Enter a number: 663
663 is not an Armstrong number
Output 2:-
Enter a number: 407
407 is an Armstrong number
Here, we ask the user
for a number and check if it is an Armstrong number. We need to calculate the
sum of cube of each digit. So, we initialize the sum to 0 and obtain each digit
number by using the modulus operator %. Remainder of a
number when it is divide by 10 is the last digit of that number. We take the cubes
using exponent operator. Finally, we compare the sum with the original number
and conclude that it is Armstrong number if they are equal.
Python Program to Find Armstrong Number in
an Interval
To understand this example, you should have knowledge of following Python programming topics:
An Armstrong number,
also known as narcissistic number, is a number that is equal to the sum of the
cubes of its own digits. For example, 371 is an Armstrong number since 371 =
3*3*3 + 7*7*7 + 1*1*1.
Source
Code
# Program to ask the user for a range and display all Armstrong numbers in that interval
# take input from the user
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num)
Output:-
Enter lower range: 100
Enter upper range: 1000
153
370
371
407
Here, we ask the user
for the interval in which we want to search for Armstrong numbers. We scan
through the interval and display all the numbers that meet the condition. We
can see that there are 4 three digit Armstrong numbers. Visit here to find out how to check if a number is Armstrong
number or not.
Python Program to Find the Sum of Natural
Numbers
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python program to find the sum of natural numbers up to n where n is provided by user
# take input from the user
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
Output:-
Enter a number: 16
The sum is 136
Here, we ask the user
for a number and display the sum of natural numbers up to that number. We use while
loop to iterate until the number becomes
zero.
We could have solved the above problem without using any loops. From
mathematics, we know that sum of natural numbers is given by n*(n+1)/2
. We could have used
this formula directly. For example, if n = 16, the sum would be (16*17)/2 = 136.
Python Program to Display Powers of 2 Using
Anonymous Function
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python Program to display the powers of 2 using anonymous function
# Take number of terms from user
terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
# display the result
for i in range(terms):
print("2 raised to power",i,"is",result[i])
Output:-
How many terms? 10
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512
In this program, we
have used anonymous (lambda) function inside the map()
built-in function to find the powers of 2.
Python Program to Find Numbers Divisible by
Another Number
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python Program to find numbers divisible by thirteen from a list using anonymous function
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
Output:-
Numbers divisible by 13 are [65, 39, 221]
In this program, we
have used anonymous (lambda) function inside the filter()
built-in function to find all the numbers
divisible by 13 in the list.
Python Program to Convert Decimal to
Binary, Octal and Hexadecimal
To understand this example, you should have knowledge of following Python programming topics:
Decimal system is the
most widely used number system. But computer only understands binary. Binary,
octal and hexadecimal number systems are closely related and we may require to
convert decimal into these systems. Decimal system is base 10 (ten symbols,
0-9, are used to represent a number) and similarly, binary is base 2, octal is
base 8 and hexadecimal is base 16.
A number with the
prefix '0b' is considered binary, '0o' is considered octal and '0x' as
hexadecimal. For example:
60 = 0b11100 = 0o74 = 0x3c
Source
Code
# Python program to convert decimal number into binary, octal and hexadecimal number system
# Take decimal number from user
dec = int(input("Enter an integer: "))
print("The decimal value of",dec,"is:")
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")
Output:-
Enter an integer: 344
The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.
In this program, we
have used built-in functions bin()
, oct()
and hex()
to convert the given decimal number into
respective number systems. These functions take an integer (in decimal) and
return a string.
Python Program to Find ASCII Value of
Character
To understand this example, you should have knowledge of following Python programming topics:
ASCII stands for American
Standard Code for Information Interchange. It is a numeric value given to
different characters and symbols, for computers to store and manipulate. For
example: ASCII value of the letter 'A' is 65. Check out the complete list of ASCII
values.
Source
Code
# Program to find the ASCII value of the given character
# Take character from user
c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))
Output 1:-
Enter a character: p
The ASCII value of 'p' is 112
Here we have used ord()
function to convert a character to an integer
(ASCII value). This function actually returns the Unicode code point of that
character. Unicode is also an encoding technique that provides a unique number
to a character. While ASCII only encodes 128 characters, current Unicode has
more than 100,000 characters from hundreds of scripts.
We can use chr()
function to inverse this process, meaning,
return a character for the input integer.
>>> chr(65)
'A'
>>> chr(120)
'x'
>>> chr(ord('S') + 1)
'T'
Python Program to Find HCF or GCD
To understand this example, you should have knowledge of following Python programming topics:
The highest common
factor (H.C.F) or greatest common divisor (G.C.D) of two numbers is the largest
positive integer that perfectly divides the two given numbers. For example, the
H.C.F of 12 and 14 is 2.
Source
Code
# Python program to find the H.C.F of two input number
# define a function
def hcf(x, y):
"""This function takes two
integers and returns the H.C.F"""
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", hcf(num1, num2))
Output:-
Enter first number: 54
Enter second number: 24
The H.C.F. of 54 and 24 is 6
This program asks for
two integers and passes them to a function which returns the H.C.F. In the
function, we first determine the smaller of the two number since the H.C.F can
only be less than or equal to the smallest number. We then use a for
loop to go from 1 to that number. In each
iteration we check if our number perfectly divides both the input numbers. If
so, we store the number as H.C.F. At the completion of the loop we end up with
the largest number that perfectly divides both the numbers.
The above method is
easy to understand and implement but not efficient. A much more efficient
method to find the H.C.F. is the Euclidean algorithm.
Euclidean
algorithm
This algorithm is
based on the fact that H.C.F. of two numbers divides their difference as well.
In this algorithm, we divide the greater by smaller and take the remainder.
Now, divide the smaller by this remainder. Repeat until the remainder is 0.
For example, if we
want to find the H.C.F. of 54 and 24, we divide 54 by 24. The remainder is 6.
Now, we divide 24 by 6 and the remainder is 0. Hence, 6 is the required H.C.F.
We can do this in Python as follows.
Source
Code
def hcf(x, y):
"""This function implements the Euclidian algorithm
to find H.C.F. of two numbers"""
while(y):
x, y = y, x % y
return x
Here we loop until y becomes zero. The statement x, y = y, x % y
does swapping of values in Python. Click here
to learn more about swapping variables in Python. In each iteration
we place the value of y in x and the remainder (x % y)
in y, simultaneously.
When y becomes zero, we have H.C.F. in x.
Python Program to Find LCM
To understand this example, you should have knowledge of following Python programming topics:
The least common
multiple (L.C.M.) of two numbers is the smallest positive integer that is
perfectly divisible by the two given numbers. For example, the L.C.M. of 12 and
14 is 84.
Source
Code to find LCM
# Python Program to find the L.C.M. of two input number
# define a function
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
Output:-
Enter first number: 54
Enter second number: 24
The L.C.M. of 54 and 24 is 216
This program asks for
two integers and passes them to a function which returns the L.C.M. In the
function, we first determine the greater of the two number since the L.C.M. can
only be greater than or equal to the largest number. We then use an infinite while
loop to go from that number and beyond. In
each iteration, we check if both the input numbers perfectly divides our
number. If so, we store the number as L.C.M. and break from the loop.
Otherwise, the number is incremented by 1 and the loop continues.
The above program is
slower to run. We can make it more efficient by using the fact that the product
of two numbers is equal to the product of least common multiple and greatest
common divisor of those two numbers.
Number1 * Number2 = L.C.M. * G.C.D.
Here is a Python
program to implement this.
Source
Code
# Python program to find the L.C.M. of two input number
# define gcd function
def gcd(x, y):
"""This function implements the Euclidian algorithm
to find G.C.D. of two numbers"""
while(y):
x, y = y, x % y
return x
# define lcm function
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
lcm = (x*y)//gcd(x,y)
return lcm
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
The output of this
program is same as before. We have two functions gcd()
and lcm()
. We require G.C.D.
of the numbers to calculate its L.C.M. So, lcm()
calls the function gcd()
to accomplish this. G.C.D. of two numbers can
be calculated efficiently using the Euclidean algorithm. Click here to learn
more about methods to calculate G.C.D in Python.
Python Program to Find Factors of Number
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python Program to find the factors of a number
# define a function
def print_factors(x):
"""This function takes a
number and prints the factors"""
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
# take input from the user
num = int(input("Enter a number: "))
print_factors(num)
Output:-
Enter a number: 320
The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320
In this program we
take a number from the user and display its factors using the functionprint_factors()
. In the function, we
use a for
loop to iterate from 1 to that number and
only print it if, it perfectly divides our number. Here, print_factors()
is a user-defined function.
Python Program to Make a Simple Calculator
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Program make a simple calculator that can add, subtract, multiply and divide using functions
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Output:-
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210
In this program, we
ask the user to choose the desired operation. Options 1,2,3 and 4 are valid.
Two numbers are taken and an if...elif...else
branching is used to execute a particular
section. User-defined functions add()
, subtract()
, multiply()
and divide()
evaluate respective operations.
Python Program to Display Calendar
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python program to display calendar of given month of the year
# import module
import calendar
# ask of month and year
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy,mm))
Output:-
Enter year: 2014
Enter month: 11
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
In this program we
import the calendar
module. We ask the user for a year and month.
The month()
function inside the
module takes in the year and the month and displays the calendar for that month
of the year.
Here we have used the
standard module calendar
that comes with Python.
Python Program to Display Fibonacci
Sequence Using Recursion
To understand this example, you should have knowledge of following Python programming topics:
A Fibonacci sequence
is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0
and 1. All other terms are obtained by adding the preceding two terms. This
means to say the nth term is the sum of (n-1)th and (n-2)th term.
Source
Code
# Python program to display the Fibonacci sequence up to n-th term using recursive functions
def recur_fibo(n):
"""Recursive function to
print Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Output:-
How many terms? 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
In this program, we
ask the user for the number of terms in the sequence. A recursive functionrecur_fibo()
is used to calculate the nth term of the
sequence. We use a for
loop to iterate and calculate each term
recursively.
Python Program to Find Sum of Natural
Numbers Using Recursion
To understand this example, you should have knowledge of following Python programming topics:
Source
Code
# Python program to find the sum of natural numbers up to n using recursive function
def recur_sum(n):
"""Function to return the sum
of natural numbers using recursion"""
if n <= 1:
return n
else:
return n + recur_sum(n-1)
# take input from the user
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Output:-
Enter a number: 16
The sum is 136
In this program, we
ask the user for a number and use recursive function recur_sum()
to compute the sum up to that number.
Python Program to Find Factorial of Number
Using Recursion
To understand this example, you should have knowledge of following Python programming topics:
The factorial of a
number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not
defined for negative numbers and the factorial of zero is one, 0! = 1.
Source
Code
# Python program to find the factorial of a number using recursion
def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
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))
Output 1:-
Enter a number: -2
Sorry, factorial does not exist for negative numbers
Output 2:-
Enter a number: 7
The factorial of 7 is 5040
Here, we ask the user
for a number and use recursive function recur_factorial()
to compute the product up to that number.