Python Programs
Python Programs
a = 0
while a < 10:
a = a + 1
print a
1 Source Code
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 (''', """).
2 Source Code
Output
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.
3 Source Code
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.
4 Source Code
Output
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.
5 Source Code
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 of y 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
x = x + y
y = x - y
x = x - y
x = x * y
y = x / y
x = x / y
XOR swap
x = x ^ y
y = x ^ y
x = x ^ y
6 Source Code
print(random.randint(0,9))
Output
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.
7 Source Code
# 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
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.
8 Source Code
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
Output
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.
9 Source Code
# In this python program, user enters a number and checked if the number is positive or
negative or zero
Here, we have used the if...elif...else statement. We can do the same thing using nested if statements as
follows.
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.
10 Source Code
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.
11 Source Code
Output 1
Output 2
12 Source Code
# Python program to find the largest number among the three input numbers
Output 1
Output 2
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.
13 Source Code
Output 1
Output 2
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 the num 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.
14 Source Code
# Python program to ask the user for a range and display all the prime numbers in that
interval
Output
Here, we take an interval from the user and find prime numbers in that range. Visit this page to understand the
code to check for prime numbers.
15 Source Code
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 using
if...elif...else statement. If the number is positive, we use for loop and range() function to calculate the
factorial.
16 Source Code
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 using
if...elif...else statement. If the number is positive, we use for loop and range() function to calculate the
factorial.
18 Source Code
# Python program to find the multiplication table (from 1 to 10) of a number input by the
user
Output
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.
19 Source Code
# Program to display the Fibonacci sequence up to n-th term where n is provided by the
user
Output
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.
20 Source Code
# Python program to check if the number provided by the user is an Armstrong number or
not
# initialise sum
sum = 0
Output 2
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.
21 Source Code
# Python program to find the sum of natural numbers up to n where n is provided by user
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.
22 Source Code
Output
In this program, we have used anonymous (lambda) function inside the map() built-in function to find the
powers of 2.
23 Source Code
# Python Program to find numbers divisible by thirteen from a list using anonymous
function
Output
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.
24 Source Code
# Python program to convert decimal number into binary, octal and hexadecimal number
system
Output
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.
25 Source Code
# define a function
def hcf(x, y):
"""This function takes two
integers and returns the H.C.F"""
return
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.
26 Source Code
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.
27 Source Code
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'
Here, ord() and chr() are built-in functions. Visit here to know more about built-in functions in Python.
# define a function
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
Output
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.
29 Source Code
while(y):
x, y = y, x % y
return x
lcm = (x*y)//gcd(x,y)
return lcm
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.
30 Source Code
# define a function
def print_factors(x):
"""This function takes a
number and prints the factors"""
print_factors(num)
Output
In this program we take a number from the user and display its factors using the function print_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.
31 Source Code
# import module
import calendar
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.
32 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)
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.
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.
33 Source Code
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)
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.
34 Source Code
Output 1
Output 2
In this program, we have take a string from the user. Using the method casefold() we make it suitable for
caseless comparisons. Basically, this method returns a lowercased version of the string. We reverse the string
using the built-in function reversed(). Since this function returns a reversed object, we use the list()
function to convert them into a list before comparing.
35 Source Code
# Program to sort alphabetically the words form a string provided by the user
In this program, we take a string form the user. Using the split() method the string is converted into a list of
words. The split() method splits the string at whitespaces. The list of words is then sorted using the sort()
method and all the words are displayed.
Source Code
# string of vowels
vowels = 'aeiou'
print(count)
Output
Enter a string: Hello, have you tried our turorial section yet?
{'e': 5, 'u': 3, 'o': 5, 'a': 2, 'i': 3}
In this program we have take a string from the user. Using the method casefold() we make it suitable for
caseless comparisions. Basically, this method returns a lowercased version of the string. We use the dictionary
method fromkeys() to construct a new dictionary with each vowel as its key and all values equal to 0. This is
initialization of the count. Next we iterate over the input string using a for loop. In each iteration we check if
the character is in the dictionary keys (True if it is a vowel) and increment the value by 1 if true.
print(count)
Explanation
The ouput of this program is the same as above. Here we have nested a list comprehension inside a dictionary
comprehension to count the vowels in a single line. However, this program is slower as we iterate over the
entire input string for each vowel.