• Home
  • |
  • Blog
  • |
  • Top 40 Python programs with source Code

March 5, 2020

Top 40 Python programs with source Code

In this Page i am gonna share 40 programs i had done in python .. Hope this will help you in your work or in your assignments.

Index and Code  by: Subarna Basnet

OUTPUTS

 

1.Write a python script to sort (ascending and descending) a dictionary by value

————————————————————————–

data={‘System ID’:2019008144,’Roll No’:190101306,’Sem’:2,’Year’:2020} 

l=list(data.values())  

l.sort()          

print("Dictionary",l)  

print(‘Ascending order is’,l)

l=list(data.values())

l.sort(reverse=True)

print(‘Descending order is’,l)

 

 

Dictionary [2, 2020, 190101306, 2019008144]

Ascending order is [2, 2020, 190101306, 2019008144]

Descending order is [2019008144, 190101306, 2020, 2]

2.Write a python script to add a key to a dictonary.hint : a.update()

—————————————————————————-

data = {0:10, 1:20, 2:30, 3:40}

print(data)

data.update({4:50})

print(data)

{0: 10, 1: 20, 2: 30, 3: 40}

{0: 10, 1: 20, 2: 30, 3: 40, 4: 50}

3.Write a Python program to iterate over dictionaries using for loops.

————————————————————————–

data = {‘A’: 10, ‘B’: 20, ‘C’: 30}

for dict_key, dict_value in data.items():

    print(dict_key,’->’,dict_value)

   

A -> 10

B -> 20

C -> 30

4.List

They maintain their ordering unless explicitly re-ordered (for example, by sorting the list).

They can be of any type, and types can be mixed.

They are accessed via numeric (zero based) indices.

List is created by placing elements in [ ] seperated by commas “, “

Dictionary

Every entry has a key and a value

Ordering is not guaranteed

Elements are accessed using key values

Key values can be of any hashtable type (i.e. not a dict) and types can be mixed

Values can be of any type (including other dict’s), and types can be mixed

 

5.Write a Python program to get the maximum and minimum value in a dictionary

————————————————————————–

data = {‘A’:2015, ‘B’:2002, ‘C’: 3900}

 

m = max(data.keys(), key=(lambda k: data[k]))

mi = min(data.keys(), key=(lambda k: data[k]))

 

print(‘Maximum Value: ‘,data[m])

print(‘Minimum Value: ‘,data[mi])

Maximum Value: 3900

Minimum Value: 2002

6.Write a program to print triangle in python. (pattern)

—————————————————————————-

print("Program to print half pyramid: ");

data = 4

 

for i in range (0, data):

    for j in range(0, i + 1):

        print("*", end=’ ‘)

 

    print("\r")

 

print("Program to print half pyramid: ")

 

data2 = 5

 

 

for i in range (data2,0,-1):

    for j in range(0, i + 1):

        print("*", end=’ ‘)

 

    print("\r")

   

print("Program to print half pyramid: ")

 

data3 = 5

 

for i in range (data3,0,-1):

    for j in range(0, i + 1):

        print(j, end=’ ‘)

 

    print("\r") 

   

print("Program to print half pyramid: ")

 

data4 = 4

 

for i in range (0,data4):

    for j in range(0, i + 1):

        print(j, end=’ ‘)

 

    print("\r")      

        

   

 

   

Program to print half pyramid:

*

* *

* * *

* * * *

 

 

 

Program to print half pyramid:

* * * * * *

* * * * *

* * * *

* * *

* *

Program to print half pyramid:

0 1 2 3 4 5

0 1 2 3 4

0 1 2 3

0 1 2

0 1

Program to print half pyramid:

0

0 1

0 1 2

0 1 2 3

7.write a program to print star patterns and alphabets pattern

————————————————————————-

print("Print Alphabets  pattern in python ")

lNumber = 6

asciiNumber = 65

for i in range(0, lNumber):

    for j in range(0, i+1):

        character  = chr(asciiNumber)

        print(character, end=’ ‘)

        asciiNumber+=1

    print(" ")

   

 

print("Program to print star pattern pyramid: \n");

 

data6 =4

for i in range (0, data6):

    for j in range(0, i + 1):

        print("*", end=’ ‘)

    print("\r")

 

for i in range (data6, 0, -1):

    for j in range(0, i -1):

        print("*", end=’ ‘)

    print("\r")

Print Alphabets pattern in python

A

B C

D E F

G H I J

K L M N O

P Q R S T U

 

 

 

 

 

 

 

 

Program to print star pattern pyramid:

 

*

* *

* * *

* * * *

* * *

* *

*

8.Store three integers in x, y and z. Print their sum.

————————————————————————

x=2

y=5

z=8

total= x+y+z

print(‘total sum of three integers’,total)

 

total sum of three integers 15

9.Store two values in x and y and swap them.

——————————————————————————

x=2

z=3

temp = x

x = z

z = temp

 

print(‘The value of x after swapping:’,x)

print(‘The value of y after swapping:’,z)

 

The value of x after swapping: 3

The value of y after swapping: 2

10.Take values of length and breadth of a rectangle from user and check if it is square or not.

——————————————————————-

l=int(input("Enter your first number :"))

 

b=int(input("Enter your second number :"))

 

if l==b:

 

 print("Its a square")

 

else :

 

 print("its an rectangle")

 

 

Enter your first number :2

 

Enter your second number :2

Its a square

11.Take name, roll number and filed of interest from user and print in the format below :

Hey, my name is xyz and my roll number is xyz. My field of interest  are xyz.

————————————————————————

print ("Enter name")

name = input()

print ("Enter roll number")

roll = input()

print ("Field of interests")

interest = input()

print ("Hey, my name is",name,"and my roll number is",roll,". My field of interests are",interest)

 

Enter name

 

Subarna

 

Enter roll number

 

190101306

Field of interests

 

Robotics

Hey, my name is Subarna and my roll number is 190101306 . My field of interests are Robotics

12.Write a program to take input from user & find square of a number

—————————————————————————

data=int(input(‘Enter any Number’))

log=data * data

print(log)

Enter any Number 4

Square of Number 16

13.Take 3 inputs from user and check :

(i) all are equal

(ii) any of two are equal ( use and or )

—————————————————————————-

print(‘Enter First Number’)

fn=int(input())

print(‘Enter Second Number’)

sn=int(input())

print(‘Enter Third Number’)

tn=int(input())

 

if fn==sn==tn:

    print(‘All are Equal’)

elif fn==sn:

    print(‘First and second are equal’)

elif sn==tn:

    print(‘Second and third are equal’)

elif fn==tn:

    print(‘First and third are equal’)

else:

    print(‘All are not equal’)

Enter First Number

 

2

Enter Second Number

 

4

Enter Third Number

 

2

First and third are equal

Enter First Number

 

2

Enter Second Number

 

2

Enter Third Number

 

2

All are Equal

14.Take two number and check whether the sum is greater than 5, less than 5 or equal to 5.

————————————————————————

print(‘Enter first Number’)

a=int(input())

print(‘Enter Second Number’)

b=int(input())

c=a+b

print(‘sum is:’,c)

if c>5:

    print(‘Sum is greater than 5’)

elif c<5 :

    print(‘Sum is less than 5’)

elif c==5:

    print(‘Sum is equal to 5’)

 

Enter first Number

2

Enter Second Number

3

sum is: 5

Sum is equal to 5

Enter first Number

2

Enter Second Number

6

sum is: 8

Sum is greater than 5

15.Suppose passing marks of a subject is 35. Take input of marks from user and check whether it is greater than passing marks or not.

———————————————————————-

print(‘Enter your marks’)

marks=int(input())

pmarks=35

 

if marks>35:

    print(‘Marks is greater than passing mark’)

else:

    print(‘Marks is lesser than passing mark’)

Enter your marks

 

60

Marks is greater than passing mark

16.A shop will give discount of 10% if the cost of purchased quantity is more than 1000.Ask user for quantity. Suppose, one unit will cost 100. Check and print total cost for user.

———————————————————————-

print ("Enter quantity")

quantity = int(input())

if quantity*100 > 1000:

  print ("Cost is",((quantity*100)-(.1*quantity*100)))

else:

  print ("Cost is",quantity*100)

                                                               

Enter quantity

 

20

Cost is 1800.0

17.A company decided to give bonus of 5% to employee if his/her year of service is more than 5 years. Ask user for their salary and year of service and print the net bonus amount.

————————————————————————–

print ("Enter salary")

salary = int(input())

print ("Enter year of service")

yos = int(input())

if yos>5:

  print ("Bonus is",.05*salary)

else:

  print ("No bonus")

Enter salary

 

15000

Enter year of service

 

6

Bonus is 750.0

18.A school has following rules for grading system:

a. Below 25 – F

b. 25 to 45 – E

c. 45 to 50 – D

d. 50 to 60 – C

e. 60 to 80 – B

f. Above 80 – A

Ask user to enter marks and print the corresponding grade.

—————————————————————————-

print ("Enter marks")

marks = int(input())

if marks<25:

  print ("F")

elif marks>=25 and marks<45:

  print ("E")

elif marks>=45 and marks<50:

  print ("D")

elif marks>=50 and marks<60:

  print ("C")

elif marks>=60 and marks<80:

  print ("B")

else:

  print ("A")

Enter marks

 

75

B

19.A student will not be allowed to sit in exam if his/her attendence is less than 75%.

Take following input from user

(i) Number of classes held

(ii) Number of classes attended.

And print percentage of class attended. Is student is allowed to sit in exam or not.

———————————————————————–

print ("Number of classes held")

noh = int(input())

print ("Number of classes attended")

noa = int(input())

atten = (noa/float(noh))*100

print ("Attendence is",atten)

if atten >= 75:

  print ("You are allowed to sit in exam")

else:

  print ("Sorry, you are not allowed. Attend more classes from next time.")

 

Number of classes held

 

90

Number of classes attended

 

70

Attendence is 77.77777777777779

You are allowed to sit in exam

20.Write a program to check if a year is leap year or not. If a year is divisible by 4 then it is leap year but if the year is century year like 2000, 1900, 2100 then it must be divisible by 400.

———————————————————————-

year = int(input("Please Enter the Year Number you wish: "))

 

if (year%400 == 0):

          print("%d is a Leap Year" %year)

elif (year%100 == 0):

          print("%d is Not the Leap Year" %year)

elif (year%4 == 0):

          print("%d is a Leap Year" %year)

else:

          print("%d is Not the Leap Year" %year)

Please Enter the Year Number you wish: 2020

2020 is a Leap Year

 

21.Ask user to enter age, sex ( M or F ), marital status ( Y or N ) and then using following rules print their place of service.

(i) if employee is female, then she will work only in urban areas.

(ii) if employee is a male and age is in between 20 to 40 then he may work in anywhere

(iii) if employee is male and age is in between 40 t0 60 then he will work in urban areas only.

And any other input of age should print "ERROR".

———————————————————————–

print ("Enter age")

age = int(input())

print ("SEX? (M or F)")

sex = input()

print ("MARRIED? (Y or N)")

marry = input()

if sex == "F" and age>=20 and age<=60:

  print ("Urban areas only")

elif sex == "M" and age>=20 and age<=40:

  print ("You can work anywhere")

elif sex == "M" and age>40 and age<=60:

  print ("Urban areas only")

else:

  print ("ERROR")

 

Enter age

 

20

SEX? (M or F)

 

M

MARRIED? (Y or N)

 

N

You can work anywhere

22.A 4 digit number is entered through keyboard. Write a program to print a new number with digits reversed as of orignal one. E.g.-

INPUT : 1234        OUTPUT : 4321

INPUT : 5982        OUTPUT : 2895

——————————————————————————-

num = int(input("Enter a number: "))

reverse_num = 0

while(num>0):

  remainder = num % 10

  reverse_num = (reverse_num * 10) + remainder

  num = num//10

print("The reverse number is : {}".format(reverse_num))

Enter a number: 9876

The reverse number is : 6789

23.          A three digit number is called Armstrong number if sum of cube of its digit is equal to number itself.

E.g.- 153 is an Armstrong number because (13)+(53)+(33) = 153.

Write all Armstrong numbers between 100 to 500.

——————————————————————————

num = int(input("Enter a number: ")) 

sum = 0 

temp = num 

 

while temp > 0: 

   digit = temp % 10 

   sum += digit ** 3 

   temp //= 10 

 

if num == sum: 

   print(num,"is an Armstrong number") 

else: 

   print(num,"is not an Armstrong number") 

Enter a number: 300

300 is not an Armstrong number

 

 

Enter a number: 153

153 is an Armstrong number

24.Take 10 integer inputs from user and store them in a list. Again ask user to give a number. Now, tell user whether that number is present in list or not.

( Iterate over list using while loop ).

—————————————————————————-

i = 10

a = []

while i>0:

  print ("Enter 5 numbers")

  num = input()

  a.append(num)

  i = i-1

print ("Enter a number to check is in list or not")

n = input()

i = 9

count = 0

while i>=0:

  if n == a[i]:

    print ("Yes its present in list")

    count = count + 1

  i = i-1

if count == 0:

  print ("No it dos not present in list")

 

 

Enter 10 numbers

 

1

Enter 10 numbers

 

2

Enter 10 numbers

 

2

Enter 10 numbers

 

3

Enter 10 numbers

 

-2

Enter 10 numbers

 

-5

Enter 10 numbers

 

9

Enter 10 numbers

 

5

Enter 10 numbers

 

8

Enter 10 numbers

 

7

Enter a number to check is in list or not

 

6

No it dos not present in list

25.Take 20 integer inputs from user and print the following:

(i) number of positive numbers

(ii) number of negative numbers

(iii) number of odd numbers

(iv) number of even numbers

(v) number of 0s.

——————————————————————————

i = 20

a = []

while i>0:

  print ("Enter number")

  num = int(input())

  a.append(num)

  i = i-1

odd = 0

even = 0

zero = 0

positive = 0

negative = 0

i = 19

while i>=0:

  if a[i] == 0:

    zero = zero+1

  elif a[i]>0:

    positive = positive + 1

    if a[i]%2 == 0:

      even = even + 1

    else:

      odd = odd + 1

  else:

    negative = negative + 1

    if a[i]%2 == 0:

      even = even + 1

    else:

      odd = odd + 1

  i = i-1

print("EVEN :",even,"ODD :"

,odd,"ZERO :",zero,"POSITIVE :",

positive,"NEGATIVE :",negative)

 

 

Enter number

 

1

Enter number

 

2

Enter number

 

-3

Enter number

 

4

Enter number

 

5

Enter number

 

6

Enter number

 

-7

Enter number

 

-8

Enter number

 

-9

Enter number

 

10

Enter number

 

0

Enter number

 

11

Enter number

 

-12

Enter number

 

13

Enter number

 

-15

Enter number

 

0

Enter number

 

0

Enter number

 

-9

Enter number

 

-5

Enter number

 

-1

EVEN : 6 ODD : 11

ZERO : 3 POSITIVE : 8 NEGATIVE : 9

26.Write a program to find the product of all elements of a list.

————————————————————————-

my_list = []

#2

for i in range(1,4):

  my_list.append(i)

#3

print(my_list)

#4

result = 1

#5

for item in my_list:

  result = result * item

#6

print("product of all elements : ",result)

[1, 2, 3]

product of all elements : 6

27.Write a program to find the product of all elements of a list.

—————————————————————————–

my_list = []

#2

for i in range(1,4):

  my_list.append(i)

#3

print(my_list)

#4

result = 1

#5

for item in my_list:

  result = result * item

#6

print("product of all elements : ",result)

[1, 2, 3]

product of all elements : 6

28.Find largest and smallest elements of a list.

————————————————————————-

a = [2,312,123,3,12,23,12,12]

largest = a[0]

i = 0

while i<len(a):

  if a[i]>largest:

    largest = a[i]

  i = i+1

print (‘Largest is :’,largest)

 

smallest = a[0]

j = 0

while i>len(a):

  if a[i]>smallest:

    largest = a[i]

  i = i+1

print (‘Smallest is :’,smallest)

Largest is : 312

Smallest is : 2

29.Write a program to print sum, average of all numbers, smallest and largest element of a list.

————————————————————————-

a = [2,312,123,3,12,23,12,12]

sumx=0

for item in a:

  sumx = sumx + item

#6

print("sum of all elements : ",sumx)

 

 

av=sumx/len(a)

print(‘Average of list is :’,av)

 

largest = a[0]

i = 0

while i<len(a):

  if a[i]>largest:

    largest = a[i]

  i = i+1

print (‘Largest is :’,largest)

 

smallest = a[0]

j = 0

while i>len(a):

  if a[i]>smallest:

    largest = a[i]

  i = i+1

print (‘Smallest is :’,smallest)

sum of all elements : 499

Average of list is : 62.375

Largest is : 312

Smallest is : 2

30.Write a program to check if elements of a list are same or not it read from front or back. E.g.-

2              3              15           15           3              2

—————————————————————————–

 

a = [1,2,3,3,2,1]

i = 0

mid = (len(a))/2

same = True

while i<mid:

  if a[i] != a[len(a)-i-1]:

    print ("Elements of list are not same")

    same = False

    break

  i = i+1

if same == True:

  print ("Elements of list are same",a)

Elements of list are same [1, 2, 3, 3, 2, 1]

31.Make a list by taking 10 input from user. Now delete all repeated elements of the list.

E.g.-

INPUT : [1,2,3,2,1,3,12,12,32]

OUTPUT : [1,2,3,12,32]

————————————————————————-

 

a = [1,2,3,2,1,3,12,12,32]

print(a)

a = list(set(a))

print (‘After deleting same elements:’,a)

[1, 2, 3, 2, 1, 3, 12, 12, 32]

After deleting same elements: [32, 1, 2, 3, 12]

32.          Take a list of 10 elements. Split it into middle and store the elements in two dfferent lists. E.g.-

INITIAL list :

58           24           13           15           63           9              8              81                1              78

After spliting :

58           24           13           15           63

9              8              81           1              78

 

—————————————————————————-

a = [58,24,13,15,63,9,8,81,1,78]

print(‘original list:’,a)

print (‘first half’,a[:len(a)//2])

print (‘second half’,a[len(a)//2:])

original list: [58, 24, 13, 15, 63, 9, 8, 81, 1, 78]

first half [58, 24, 13, 15, 63]

second half [9, 8, 81, 1, 78]

33.Write a program to find the length of the string "refrigerator" without using len function

————————————————————————

string="refrigerator"

count=0

for i in string:

      count=count+1

print("Length of the string is:")

print(count)

 

Length of the string is:

12

34.Write a program to check if the letter ‘e’ is present in the word ‘Umbrella’.

—————————————————————————

string = "Umbrella"

 

if "e" in string:

      print ("letter e is present in Umbrella")

letter e is present in Umbrella

35.Write a program to make a new string with all the consonents deleted from the string "Hello, have a good day".

————————————————————————

a = [‘a’,’e’,’i‘,’o’,’u’,’A’,’E’,’I’,’O’,’U‘,’ ‘]

b = "Hello, have a good day"

print(b)

for i in b:

  if i not in a:

    b = b[:b.index(i)]+b[b.index(i)+1:]

print (‘only Vowels :’,b)

Hello, have a good day

only Vowels : eo ae a oo a

36.You are given with a list of integer elements. Make a new list which will store square of elements of previous list.

————————————————————————-

a=[1,2,3,4,5,6,7,8,9,0]

print(a)

b=[]

for i in a:

 b.append(i**2)

print(b)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

[1, 4, 9, 16, 25, 36, 49, 64, 81, 0]

 

37.Using range(1,101), make two list, one containing all even numbers and other containing all odd numbers.

————————————————————————–

even=[]

odd=[]

for i in range(1,101):

  if i%2 == 0:

    even.append(i)

  else:

    odd.append(i)

 

print(even)

print(odd)

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

38.From the two list obtained in previous question, make new lists, containing only numbers which are divisible by 4, 6, 8, 10, 3, 5, 7 and 9 in separate lists.

————————————————————————

ven=[]

odd=[]

 

for i in range(1,101):

  if i%2 == 0:

    even.append(i)

  else:

    odd.append(i)

   

 

final=[]

for j in even:

    if (j%4==0) or (j%6==0) and (j%8==0) or (j%10==0) or (j%3==0) or (j%5==0) or (j%7==0) or (j%9==0):

        final.append(j) 

for j in odd:

    if (j%4==0) or (j%6==0) and (j%8==0) or (j%10==0) or (j%3==0) or (j%5==0) or (j%7==0) or (j%9==0):

        final.append(j) 

No divisible by: [4, 6, 8, 10, 12, 14, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 44, 48, 50, 52, 54, 56, 60, 64, 66, 68, 70, 72, 76, 78, 80, 84, 88, 90, 92, 96, 98, 100, 3, 5, 7, 9, 15, 21, 25, 27, 33, 35, 39, 45, 49, 51, 55, 57, 63, 65, 69, 75, 77, 81, 85, 87, 91, 93, 95, 99]

39.Use dictionary to store antonyms of words. E.g.-Right’:’Left‘, ‘Up’:’Down‘, etc. Display all words and then ask user to enter a word and display antonym of it.

————————————————————————-

word = {‘right’:’left’,’up’:’down’,’good’:’bad’,’cool’:’hot’,’east’:’west’}

print ("Enter any word from following words")

for i in word.keys():

                print (i)

user_input = input()

if word.get(user_input):

                print ("Antonym of",user_input,"is",word[user_input])

else:

                print ("Enter correct input")

Enter any word from following words

right

up

good

cool

east

 

right

Antonym of right is left

40.Take a list containing only strings. Now, take a string input from user and rearrange the elements of the list according to the number of occurrence of the string taken from user in the elements of the list.

E.g.-LIST : ["no bun","bug bun bug bun bug bug","bunny bug","buggy bug bug buggy"]

STRING TAKEN : "bug"

OUTPUT LIST:["bug bun bug bun bug bug","buggy bug bug buggy","bunny bug","no bun"]

——————————————————————————

a = ["apple banana apple banana","banana apple banana","banana banana","apple apple apple banana","no banana"]

print(a)

print(‘Enter any word to rearrange’)

b = input()

c = {}

for i in a:

  count = 0

  for j in i.split():

    if j == b:

      count = count+1

  c[count]=i

d = []

for s in sorted(c):

  d.append(c[s])

d.reverse()

print (d)

[‘apple banana apple banana’, ‘banana apple banana’, ‘banana banana‘, ‘apple apple apple banana’, ‘no banana’]

Enter any word to rearrange

 

apple

 

[‘apple apple apple banana’, ‘apple banana apple banana’, ‘banana apple banana’, ‘no banana’]

 

Download Link: https://drive.google.com/file/d/1hB5S-3BaeFEoLkgFne8bUBRgZ2azoGVU/view?usp=sharing

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Related Posts

Free Responsive Form made in Html & CSS

Free Dynamic Video player made in HTML&CSS

How I made COVID-19 Mailer program from Python

>