Python Programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

1 line: Output

print 'Hello, world!'

2 lines: Input, assignment

name = raw_input('What is your name?\n')


print 'Hi, %s.' % name

3 lines: For loop, built-in enumerate function, new style formatting

friends = ['john', 'pat', 'gary', 'michael']


for i, name in enumerate(friends):
print "iteration {iteration} is {name}".format(iteration=i, name=name)

4 lines: Fibonacci, tuple assignment

parents, babies = (1, 1)


while babies < 100:
print 'This generation has {0} babies'.format(babies)
parents, babies = (babies, parents + babies)

a = 0
while a < 10:
a = a + 1
print a

1 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 (''', """).
2 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.

3 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.
4 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.

5 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 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

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

6 Source Code

# Program to generate a random number between 0 and 9

# import the random module


import random

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

# 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

8 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

9 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.
10 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.

11 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.

12 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.
13 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 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

# 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

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

# 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 using
if...elif...else statement. If the number is positive, we use for loop and range() function to calculate the
factorial.

16 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 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

# 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.

19 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.

20 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.

21 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.
22 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.

23 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.
24 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.

25 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.

26 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.

27 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'

Here, ord() and chr() are built-in functions. Visit here to know more about built-in functions in Python.

28 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.

29 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.
30 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 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

# 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.

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)

# 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.

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

# 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.
34 Source Code

# Program to check if a string


# is palindrome or not

# take input from the user


my_str = input("Enter a string: ")

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")

Output 1

Enter a string: aIbohPhoBiA


It is palindrome

Output 2

Enter a string: palindrome


It is not palindrome

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

# take input from the user


my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = my_str.split()

# sort the list


words.sort()

# display the sorted words


for word in words:
print(word)
Output

Enter a string: Hello this Is an Example With cased letters


Example
Hello
Is
With
an
cased
letters
this

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

# Program to count the number of each vowel in a string

# string of vowels
vowels = 'aeiou'

# take input from the user


ip_str = input("Enter a string: ")

# make it suitable for caseless comparisions


ip_str = ip_str.casefold()

# make a dictionary with each vowel a key and value 0


count = {}.fromkeys(vowels,0)

# count the vowels


for char in ip_str:
if char in count:
count[char] += 1

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.

We can do the same thing using a dictionary comprehension.


36 Source Code

# Program to count the number of


# each vowel in a string using
# dictionary and list comprehension

# take input from the user


ip_str = input("Enter a string: ")

# make it suitable for caseless comparisions


ip_str = ip_str.casefold()

# count the vowels


count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'}

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.

You might also like