Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

Python Programs

The document provides examples of Python programs to perform tasks like currency conversion, unit conversion, pattern printing, finding common items in lists, selecting even/odd items from a list, performing set operations and sorting a dictionary. The programs demonstrate basic Python constructs like loops, conditional statements, lists, tuples, sets and dictionaries.

Uploaded by

sanskar phadke
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Python Programs

The document provides examples of Python programs to perform tasks like currency conversion, unit conversion, pattern printing, finding common items in lists, selecting even/odd items from a list, performing set operations and sorting a dictionary. The programs demonstrate basic Python constructs like loops, conditional statements, lists, tuples, sets and dictionaries.

Uploaded by

sanskar phadke
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Programs

1, Program to convert U.S. dollars to Indian


dollars rupees.
float(input("Please
rupees = dollars 70
enter
dollars: "))
print("Dollars: "dollars)
print("Rupees: ".rupees)
Output:
Please enter dollars:5e
Dollars: 5e.0
Rupees: 3500.0
2. Program to convert bits to Megabytes,
Gigabytes and Terabytes.
b=float (input("Enter Number of Bytes: "))
kb=b/1024
mb=b/ (1024*1024)
gb=b/(1024*1024*1024)
tb=b/ (1024*1024*1024*1024)
print("Bytes=".b, "Kilobyte=", kb)
print("Bytes=",b, "Megabyte=", mb)
print("Bytes=", b, "Gigabyte=", gb)
print("Bytes=", b, "Terabyte=", tb)
Output:
Enter Number of Bytes: 5
Bytes 50.0 Kilobyte= 0.048828125
Bytes= 50.0 Megabyte= 4.76837158203125e-05
Bytes= 50.0 Gigabyte= 4.6566128730773926e-08
Bytes= 50.0 Terabyte= 4.547473508864641e-11
3. Program to check i f a number is positive, negative or zero.
number=int(input("Enter any number: "))
if(number<@):
print(number, "" is negative number")

elif (number>0):
print(number," is positive nnumber")
else:
print(number, " is zero")

Output:
Enter any number: -10
10 is negative number
4 Print the following patterns using loop:
4
***

***

for i in range(3):
'*(3-i-1) + '*'*(2*1+1))
print('

for j in reversed (range(2)):


+ '***(2*j+1))
print(' '*(2-3)
P.1
P.2 Programs
Programming with Python'
Output: *

**

******

***

5. Print the following patterns using loop


1010101
10101
101
1
i-3
j=
k=
while(i>=0):
a" "*k+"10"*i+"1"+" "*i
print(a)
i=i-1
j=j+2
k=k+1
if(ic0 and j>=4):
break
Output:
1010101
10101
101

1 using for loop.


of first 10 natural numbers
6. Python program to find the sum
sum=0
for i in range(0, 10) :
print(i)
sum=sum+i

print("Sum of numbers= ", sum)


Output:

3
4
5
6

8
9
Sum of numbers= 45
items in a list.
7. Python program to sum and multiplication of all the
sum=0
mul:l=1
list1 [2,3,4,5,6]
for ele in range (0, len(list1)):
sum Sum +list1[ele]
mul = mul*list1[ele]
print("Sum of all elements in given list: ", s um)
print("Multiplication of all elements in given 1ist: ", mul)
Output:
Sum of all elements in given list: 20
Multiplication of all elements in given list: 720
Programming with 'Python' 3 Programs
8. Python program to get the largest number,amallest number and reverse thelist.
listi [12, 3, 48, 10, 36]
print("Smallest Vumber in list: ",min(11st1))
print("Largest Number in l1st: ",max(1ist1))
list1.reverse()
print("Reverse list: ",list1)
Output:
Smallest Number in l1st: 3
Largest Number in 1ist: 48
Reverse list: [36, 10, 48, 3, 12]1
9. Python program to find common items from two lists.
listi = [10, "Green",20, "Red"]
list2 = [30, "Green", 10, "Pink"]
print (set (list1) & set (list2))
Output:
(10, Green")
10. Python program to select the even items of a list.
list1 [(12, 3, 48, 10, 36]
even=[
odd=[]
for j in list1:
if(j%2==0):
even.append(j)
else:
odd.append (j)
print("The even list", even)
print("The odd list", odd)
Output:
The even list [12, 48, 10, 36]
Theodd list [3]
maximum number from it.
11. Create a tuple and find the minimum and
tup1=(11,2,3)
print("maximum element of tuple: ", max(tup1))
print("minimum element of tuple:", min(tup1)

Output: 11
maximum element of tuple:
minimum element of tuple: 2 items of a tuple.
12. Python program to find the repeated
4, 7
tupl =
2, 4, 5, 6, 2, 3, 4,
print(tupl)
count tupl.count(4)
print(count)
Output:
(2, 4, 5, 6, 2, 3, 4, 4, 7)
Two Three Four.
13. Print the number in words
for example: 1234 => One 'Six', 'Seven', 'Eight
'Four', Five',
['Zero', 'One', 'Two', "Three',
ones
Nine']
num=input("enter a number")
print(num)
Word-[1
for a in num:
Word.append(ones[int(a)])
print (word)
Output:
enter a number1234

1234
'Three, "Four
One', 'Two',
Programming with Python" P.4
remove
one item from ses
et.
PIogam
and
in a set
14.
Python program
set1=
to create a set, add
member(s)

{0, 2, 4, 6, 83
set1.add (10)
set1.add (12)
print("After Addition", set1)
set1.remove (0)
print("After Deletion", set1)
Output:
After Addition {0, 2, 4, 6, 8, 10, 12)
After Deletion {2, 4, 6, 8, 10, 12) set:
intersection
ot sets, union of sete, set
operations on
*
program to perform following
clear a set.
difference, symmetric difference,
A {0, 2, 4, 6, 8);
B {1, 2, 3, 4, 5};
print("Union : ", A| B)
print("Intersection: ", A & B)
print("Difference ", A B)
print("Symmetric difference ", A
^
B)
Output:
Union {0, 1, 2, 3, 4, 5, 6, 8}
Intersection: {2, 4}
Difference: {0, 8, 6}
Symmetric difference {e, 1, 3, 5, 6, 8 of set.
value and length
to find maximum and the minimum
16. Python program
set1= {0, 2, 4, 6, 8}
print("Maximum value in set", max(set1) )
print("minimum value in set",min(set1))
print("length of set",len (set1))
Output:
Maximum value in set 8
minimum value in set

length of set 5
and descending) a dictionary by value.
17. Python script to sort (ascending
import operator
"Two", 3: "Three", 4: "Four", 0:"zero"}
d {1:
= "One", 2:
print('Original dictionary ',d)
key=operator. itemgetter (0))
sorted_d =sorted(d.items (), ', sorted_d) by value :
print('Dictionary in
ascending order
key=operator. itemgetter (0), reverse=True)
sorted_d sorted(d.items(),
=

print('Dictionary in descending
order by value ',sorted_d)
Output: 4: 'Four', 0: ' zero'}
Original dictionary {1: "One', 2: 'Two, 3: 'Three', 'Two'), (3
value [(e, 'zero'), (1, 'One'),. (2,
Dictionary in ascending order by
Three'), (4, 'Four")]
Dictionary in descending
order by value : [(4, 'Four ), (3, 'Three '), (2, "TwO )»
(1, 'One'), (0, 'zero')]
dictionaries to create a new one.
18. Python script to concatenate following
Sample Dictionary:
dic1 = {1:10, 2:20}
dic2 = {3:30, 4:40}
dic3 = {5:50,6:60}
dic1={1:10, 2:20}
dic2={3:30, 4:40}
PS
Programming with Python'
dic3={5:50,6:60)
dic4 {})
for d in (dic1, dic2, dic3):
dic4.update(d)
print (dica)
Output:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 5e, 6: 6e)
19. Python program to combine two dictionary adding vahves for common key
d1 {'a': 100, b20e, 3 0 0
d2 'a': 300, 'b': 200, d:400)
from collections import Counter
d1 {'a': 100, 'b': 200, 't':300)
d2 {'a': 300, b': 200, 'd':400)
d Counter (d1) + Counter (d2)
print(d)
Output:
Counter({a": 400, b': 400, 'd: 400, '300)))
20. Python program to print all unique values in a dictionary
Sample Data V: "Se01"), ("v: se02"), ('VI
"VII": "Sees"), ("v": "see9"), {("VIII°: "se7"}]
L I"V":"see1"), {("V": "s002"), ("VI": "see1"), (VI"
"V": "See9"),{"VIII": "see7"}]
print("Original List: ", L)
u_value set(val for dic in L for val in dic.values())
print("Unique Values: ",u_value)
Output: saas
Original (V List: 'see1'}, ('v' : 'See2'), (V
{'VII': 'see5'}, { V°: 'S0e9"}, ('VIII': "Se07'})
Unique Values:'See1", 'see7", 's005", 'see2", 'see9
21. Python program to find the highest 3 values in dictionary.
a

from heapq import nlargest


dict1{'a':50e, 'b':600, 'c': 568, 'd' :400, 'e':880, f 2 0 )

largest3 nlargest (3, dictl, key=dict1.get)


print (largest3)
Output:
'e', 'b' ' number of upper case letters and lower

22. Python function that accepts a string and calculate the


case letters.
def string_test(s):
d={"UPPER_CASE:0, "LOWER_CASE":0)
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else
pass
print ("original String c, h as)r a c t e r s " , d["UPPER_CASE"|)
print ("No. of Upper
case
d["tOWER_CASE"])
case C h a r a c t e r s " ,
print ("No. of Lower
Programaning')
string_test( 'Hello Python
Output: Programning
Original String: Hello Python
characters3
No. of Upper case Characters 19
case
No. of Lower
23. Python program to generate a random float where the value is between S and 50 using Pyt
math module. ython
import random
print("Random float number between given range is ", random.uniform(5,50))
Output:
Random Float number between given range is 22.00227692464644
24. Python function that takes a number as a parameter and check the number 1s prime or not.

def prime (n):


for i in range(2,n+1):
ifn%i==0
break
if i-=n:
print(n," is prime number")
else:
print(n," is not a prime number")

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


prime (n1)
Output:
Enter a number:6
6 isfunction
25. Python not a prime number the factorial of a number (a non-negative integer). The function
to calculate
accepts the number as an argument.
def fact(num):
fact-1
if num« 0:
print("Sorry, factorial does not exist for negative numbers")
e l i f num == 0:
print("The factorial of e is 1")
else:
for i in range(1, num + 1):
fact=fact*i
print("The factorial of ", num," is ", fact)

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


fact(n1)
Output:
Enter a number:5

The factorial of 5 is 120 Math module.


area and circumference of circle using inbuilt
26. Python program that will calculate
import math
the radius of the circle : '))
r
area
float (input( Enter
= math.pi *r * r

circum=2 * math.pi * r

print("Area circle i s : %.2f" %area)


of the
print("Circumference of the circle is : %.2f" %circum)

Output:
Enter the radius of the circle :6
Area of the circle is : 113.10
is 37.70
Circumference of the circle :

month using calendar module.


27. Python program that will display Calendar of given
import calendar
yy 2020
mm = 1
print(calendar .month (yy, mm))
Programming with 'Python' P.7
Output:
Program
January 2020
Mo Tu We ThFrSa 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 31
28. Python program to create two matrices and perform addition, subtraction, multiplication
division operation on matrix. and
import numpy
x
numpy. array([[1, 2],
=

[4, 5]])
y numpy.array([[7, 8], [9, 10]])
print ("The element wise addition of matrix is ")
print (numpy.add(x,y))
print ("The element wise subtraction of matrix is
print (numpy.subtract (x, y)) ")
print ("The element wise division of matrix is
")
print (numpy.divide(x, y))
print ("The element wise multiplication of
print (numpy.multiply(x,y)) matrix is: ")
print ("The product of matrices is: ")
print (numpy.dot (x, y))
Output:
The element wise addition
of matrix is
[[ 8 10]
[13 15]]
The element wise subtraction of matrix is
[-6-6]
[-5-5]1
The element wise division of matrix is
[[e.14285714 0.25
[0.44444444 0.5 i
The element wise multiplication of matrix is
[[ 7 16]
[36 50]1
The product of matrices is
[[25 28]
[73 82]]
29. NumPy program to generate six random integers between 10 and 30.
import numpy as npP
x = np.random. randint (low-10, high=30, size=6)
print(x)
Output:
27[2719 26 28 26 12]
30. Python program to create a class to print an integer and a character with two methods having
the same name but different sequence of thhe integer and the character parameters. For example,

if the parameters ofthe first method are of the form (int n, char c), then that of the second
method will be of the form (char c, int n)
class Display:
def printmsg(self, x, y):
if type(x)== int:
print("Integer Message=" ,x);
ogrammingwith 'Python' P.8
else:
Programe9
print("Character Message=" ,x);
a=Display ();
a.printmsg(20, "Meenakshi')
a.printmsg( "Meenakshi ' ,20)
Output:
Integer Message= 20
Character Message Meenakshi
31. Python program to create a class to print the area of a square and a rectangle. The class has two
methods with the same name but different number of parameters. The method for printing area
of rectangle has two parameters which are length and breadth respectively while the other
method for printing area of square has one parameter which is side of square.
class Area:
def print Area(self, x, y=None):
if y is not None:
print( "Area of Rectangle=", xy)
else:
print("Area of Square=", x*x);
a=Area()
a.printArea (10)
a.printArea (10,20)
32. Python program to create a class 'Degree' having a method 'getDegree' that prints "I got a

degree". It has two subclasses namely 'Undergraduate' and 'Postgraduate' each havinga method
with the same name that prints "I am an Undergraduate" and "I ama Postgraduate" respectively.
Call the method by creating an object of each of the three classes.
class Degree:
def getDegree ( self):
print("I got a diploma degree")
class Undergraduate(Degree):
def getDegree(self):
print("I got a undergraduate degree")
class Postgraduate(Degree):
def getDegree(self):
print("I got a postgradyate degree")
d=Degree()
u=Undergraduate ()
p-Postgraduate()
d.getDegree()
u.getDegree()
P.getDegree()
Output:
I got a diploma degree
I got a undergraduate degree
I got a postgradyate degree

You might also like