0% found this document useful (0 votes)
2 views52 pages

Python Practical File Final

The document outlines a series of practical programming exercises, each demonstrating different coding tasks in Python. These tasks include basic operations like printing, arithmetic calculations, and input handling, as well as more complex functions like calculating factorials, generating Fibonacci series, and working with lists. Each practical includes code snippets, expected outputs, and confirms successful execution.

Uploaded by

wadhwasanya6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views52 pages

Python Practical File Final

The document outlines a series of practical programming exercises, each demonstrating different coding tasks in Python. These tasks include basic operations like printing, arithmetic calculations, and input handling, as well as more complex functions like calculating factorials, generating Fibonacci series, and working with lists. Each practical includes code snippets, expected outputs, and confirms successful execution.

Uploaded by

wadhwasanya6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Practical-1

Write a program to show an output on the screen

Code:
print("Hello World!")

Output:
Hello World!

=== Code Execution Successful ===

Practical-2
Write a program to add 2 numbers

Code:
a=int(input("Enter a number:"))
b=int(input("Enter another number:"))
print(a+b)

Output:
Enter a number:23
Enter another number:3
26

=== Code Execution Successful ===


Practical-3
Write a program to calculate the area of a triangle

Code:
a=int(input("Enter the height of the triangle:"))
b=int(input("Enter the base of the triangle:"))

print(0.5*a*b)

Output:
Enter the height of the triangle:5
Enter the base of the triangle:4
10.0

=== Code Execution Successful ===


Practical-4
Write a program to calculate the square root of a number

Code:
a=int(input("Enter the number you want the square root of:"))
print(a**0.5)

Output:
Enter the number you want the square root of:9
3.0

=== Code Execution Successful ===


Practical-5
Write a program to swap two numbers

Code:
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
c=a
a=b
b=c
print("The value of a is",a)
print("The value of b is",b)

Output:
Enter the value of a:2
Enter the value of b:3
The value of a is 3
The value of b is 2

=== Code Execution Successful ===


Practical-6
Write a program to convert km into miles

Code:
print("Enter what do you wanna convert: \n 1)Miles to km \n 2)Km to miles")
a=int(input())
if(a==1):
miles=int(input("Enter value:"))
km=miles*1.609
print("Value in km is:\n",km)
elif(a==2):
km=int(input("Enter value:"))
miles=km/1.609
print("Value in miles is:\n",miles)
else:
print("Invalid option")

Output:
Enter what do you wanna convert:
1)Miles to km
2)Km to miles
2
Enter value:2
Value in miles is:
1.2430080795525171
=== Code Execution Successful ===
Practical-7
Write a program to convert celsius into Fahrenheit

Code:
print("Enter what do you wanna convert: \n 1)celsius into fahrenheit \n
2)fahrenheit into celsius")
a=int(input())
if(a==1):
celsius=int(input("Enter value:"))
fahrenheit= (celsius * 9/5) + 32
print("Value in fahrenheit is:\n",fahrenheit)
elif(a==2):
fahrenheit=int(input("Enter value:"))
celsius=(fahrenheit - 32) * 5/9
print("Value in miles is:\n",celsius)
else:
print("Invalid option")

Output:
Enter what do you wanna convert:
1)celsius into fahrenheit
2)fahrenheit into celsius
1
Enter value:36
Value in fahrenheit is:
96.8
Practical-8
Write a program to solve a quadratic equation

Code:
import cmath

a = int(input("Enter the value of a:"))


b = int(input("Enter the value of b:"))
c = int(input("Enter the value of c:"))

d = (b**2) - (4*a*c)

sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

or
print("Create a quadratic equation:\n ax^2+bx+c")
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
c=int(input("Enter the value of c:"))

root1=(-b+((b**2-4*a*c))**0.5)/(2*a)
root2=(-b-((b**2-4*a*c))**0.5)/(2*a)

print("The first root of the equation is:\n",root1)


print("The second root of the equation is:\n",root2)
=== Code Execution Successful ===

Output:
Enter the value of a:2
Enter the value of b:-1
Enter the value of c:-6
The solution are (-1.5+0j) and (2+0j)

=== Code Execution Successful ===

or
Create a quadratic equation:
ax^2+bx+c
Enter the value of a:2
Enter the value of b:-1
Enter the value of c:-6
The first root of the equation is:
2.0
The second root of the equation is:
-1.5

=== Code Execution Successful ===


Practical-9
Write a program to generate a random number

Code:
import random

a= random.randint(1,100)
print(a)

Output:
81

=== Code Execution Successful ===


Practical-10
Write a program to check if a number is positive, negative or
zero

Code:
a=int(input("Enter any integer number:"))

if(a==0):
print("The number is zero")
elif(a<0):
print("The number is a negative number")
else:
print("The number is a positive number")
Output:
Enter any integer number:0
The number is zero

=== Code Execution Successful ===


Practical-11
Write a program to check if a number is odd or even

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

if(a%2==0):
print("it's an even number")
else:
print("it's an odd number")

Output:
Enter a number:6
it's an even number

=== Code Execution Successful ===


Practical-12
Write a program to check leap year

Code:
year=int(input("Enter a year:"))

if(year%4==0):
print("it's an leap year")
else:
print("it's not a leap year")

Output:
Enter a year:2004
it's an leap year

=== Code Execution Successful ===


Practical-13
Write a program to find the largest number among three numbers

Code:
a=int(input("Enter a number A:"))
b=int(input("Enter a number B:"))
c=int(input("Enter a number C:"))

if(a>b and a>c):


print("A is the largest number")
elif(b>a and b>c):
print("B is the largest number")
else:
print("C is the largest number")

Output:
Enter a number A:23
Enter a number B:33
Enter a number C:44
C is the largest number

=== Code Execution Successful ===


Practical-14
Write a program to check whether the given program is prime
number or not

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

if(a==0 or a%2==0):
print("The number is a even number")
else:
print("The number is a odd number")

Output:
Enter a number:3
The number is a odd number

=== Code Execution Successful ===


Practical-15
Write a program print all prime numbers in a given interval

Code:
lower=int(input("Enter the lowest value for the interval:"))
upper=int(input("Enter the highest value for the interval:"))

print("The prime numbers are:\n")


for number in range(lower,upper+1):
if(number>1):
for i in range(2,number):
if(number%i==0):
break
else:
print(number,end=",")

Output:
Enter the lowest value for the interval:1
Enter the highest value for the interval:100
The prime numbers are:
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,
=== Code Execution Successful ===
Practical-16
Write a program to find the factorial of a number

Code:
number=int(input("Enter the number you want the factorial of:"))

factorial=1
if(factorial==0):
print("The factorial of 0 is 1")
else:
for i in range(1,number+1):
factorial = factorial*i
print("The factorial of",number,"is",factorial)

Output:
Enter the number you want the factorial of:4
The factorial of 4 is 24

=== Code Execution Successful ===


Practical-17
Write a program to display the multiplication table

Code:
number=int(input("Enter the number you want the table of:"))
print("The table of",number,"is:")
for i in range(1,11):
print(number,"x",i,"=",number*i)

Output:
Enter the number you want the table of:4
The table of 4 is:
4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

=== Code Execution Successful ===


Practical-18
Write a program to print the Fibonacci series

Code:
n=int(input("Enter length of the series:"))
num1 = 0
num2 = 1
next_number = num2
count = 1

while count <= n:


print(next_number, end=" ")
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print()

Output:
Enter length of the series:6
1 2 3 5 8 13

=== Code Execution Successful ===


Practical-19
Write a program to find if the given number is Armstrong
number or not

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

sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit * digit * digit
temp = temp//10

if sum==num:
print('It is an Armstrong number')
else:
print('It is not an Armstrong number')

Output:
Enter 3-digit number : 153
It is an Armstrong number

=== Code Execution Successful ===


Practical-20
Write a program to find Armstrong number in the given interval

Code:
lower = int(input("Enter the lower bond : "))
upper = int(input("Enter the upper bond : "))
for num in range(lower,upper+1):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp = temp//10

if sum==num:
print(num)

Output:
Enter the lower bond : 10
Enter the upper bond : 1000
153
370
371
407
Practical-21
Write a program to calculate the sum of natural numbers

Code:
a=int(input("find sum of all natural numbers till:"))

for num in range(0,a):


sum = 0
while num>0:
sum+=num
num-=1
print("The sum is", sum)

Output:
find sum of all natural numbers till:4
The sum is 6

=== Code Execution S


Practical-22
Write a program to implement the following functions:-
Count(), find(), capitalize(), title(), lower(), upper(), swapcase(),
replace(), join(), isspace(), isdigit(), split(), startswith(),
endswith().

Code:
string="This is a random string in which we are gonna perform some basic
STRING FUNCTIONS on!!"
print(string,"\n")

new=str.upper(string)
print("upper():\n",new)
new=str.lower(string)
print("lower():\n",new)
new=string.replace("basic","advance")
print("replace():\n",new)
new=string.count("r")
print("count(r):\n",new)
new=string.find("r")
print("find(r):\n",new)
new=str.capitalize(string)
print("capitalize():\n",new)
new=str.title(string)
print("title():\n",new)
new=str.swapcase(string)
print("swapcase():\n",new)
new="S".join(string)
print("join():\n",new)
new=str.isspace(string)
print("isspace():\n",new)
new=str.isdigit(string)
print("isdigit():\n",new)
new=str.split(string)
print("split():\n",new)
new=string.startswith("T")
print("startswith():\n",new)
new=string.endswith("T")
print("endswith():\n",new)

Output:
This is a random string in which we are gonna perform some basic STRING
FUNCTIONS on!!

upper():
THIS IS A RANDOM STRING IN WHICH WE ARE GONNA PERFORM SOME BASIC
STRING FUNCTIONS ON!!
lower():
this is a random string in which we are gonna perform some basic string
functions on!!
replace():
This is a random string in which we are gonna perform some advance STRING
FUNCTIONS on!!
count(r):
5
find(r):
10
capitalize():
This is a random string in which we are gonna perform some basic string
functions on!!
title():
This Is A Random String In Which We Are Gonna Perform Some Basic String
Functions On!!
swapcase():
tHIS IS A RANDOM STRING IN WHICH WE ARE GONNA PERFORM SOME BASIC
string functions ON!!
join():
TShSiSsS SiSsS SaS SrSaSnSdSoSmS SsStSrSiSnSgS SiSnS SwShSiScShS SwSeS
SaSrSeS SgSoSnSnSaS SpSeSrSfSoSrSmS SsSoSmSeS SbSaSsSiScS SSSTSRSISNSGS
SFSUSNSCSTSISOSNSSS SoSnS!S!
isspace():
False
isdigit():
False
split():
['This', 'is', 'a', 'random', 'string', 'in', 'which', 'we', 'are', 'gonna', 'perform',
'some', 'basic', 'STRING', 'FUNCTIONS', 'on!!']
startswith():
True
endswith():
False
Practical-23
Write a program to access a list using the following:-
Indexing, negative indexing and slicing

Code:
list1=["hi","bye",1,2,3,"hehe"]
print("List:",list1)
print("By indexing:",list1[1])
print("By negative indexing:",list1[-1])
print("By slicing:",list1[1:4])

Output:
List: ['hi', 'bye', 1, 2, 3, 'hehe']
By indexing: bye
By negative indexing: hehe
By slicing: ['bye', 1, 2]

=== Code Execution Successful ===


Practical-24
Write a program to check if a list is empty or not

Code:
list1=[]
if(len(list1)==0):
print("The list is empty")
else:
print("The list is not empty")

Output:
The list is empty

=== Code Execution Successful ===


Practical-25
Write a program to concatenate two lists

Code:
print("concatenation of two lists")
list1=["hi","bye",1,2,3,"hehe"]
list2=[44,"none",True]
list3=list1+list2
print(list3)

# or

for x in list2:
list1.append(x)

print(list1)

Output:
concatenation of two lists
['hi', 'bye', 1, 2, 3, 'hehe', 44, 'none', True]
['hi', 'bye', 1, 2, 3, 'hehe', 44, 'none', True]

=== Code Execution Successful ===


Practical-26
Write a program to get the last element of the list

Code:
list1=["hi","bye",1,2,3,"hehe"]
print("inputed list:",list1)

print("Last element of the input list = ",list1.pop())

Output:
inputed list: ['hi', 'bye', 1, 2, 3, 'hehe']
Last element of the input list = hehe

=== Code Execution Successful ===


Practical-27
Write a program to find lowest common factor

Code:
def compute_lcm(x,y):
if(x>y):
greater=x
else:
greater=y
while(True):
if(greater%x==0) & (greater%y==0):
lcm=greater
break
greater+=1
return lcm
print("Enter the numbers you want to find the LCM of:")
x=int(input("First number:"))
y=int(input("second number:"))
print("the lcm is:",compute_lcm(x,y))

Output:
Enter the numbers you want to find the LCM of:
First number:12
second number:4
the lcm is: 12
=== Code Execution Successful ===
Practical-28
Write a program to make a simple calculator

Code:
def add(x,y):
return x+y
def sub(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y

print("Select
operation:\n1)Addition\n2)Subtraction\n3)Multiplication\n4)Division\n5)Exit")

while True:
choice=int(input("Enter the operation you want to perform:"))
x=int(input("Enter the value for x:"))
y=int(input("Enter the value for y:"))

if(choice==1):
print(add(x,y))
elif(choice==2):
print(sub(x,y))
elif(choice==3):
print(multiply(x,y))
elif(choice==4):
print(divide(x,y))
elif(choice==5):
break
else:
print("Invalid operation")
continue

Output:
Select operation:
1)Addition
2)Subtraction
3)Multiplication
4)Division
5)Exit
Enter the operation you want to perform:3
Enter the value for x:4
Enter the value for y:54
216
Enter the operation you want to perform:
Practical-29
Write a program to find the ASCII value of a number

Code:
character=input("Enter any character or a number:")
print("The ASCII value of the given character is", ord(character))

Output:
Enter any character or a number:_
The ASCII value of the given character is 95

=== Code Execution Successful ===


Practical-30
Write a program to display a Calendar

Code:
import calendar

yy = int(input("Enter year: "))


mm = int(input("Enter month: "))

print(calendar.month(yy, mm))

Output:
Enter year: 2024
Enter month: 11
November 2024
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

=== Code Execution Successful ===


Practical-31
Write a program to convert decimal to binary , octal and
hexadecimal

Code:
dec = int(input("Enter a decimal value:"))

print("The decimal value of", dec, "is:")


print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")

Output:
Enter a decimal value:344
The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

=== Code Execution Successful ===


Practical-32
Write a program to find the factors of a number

Code:
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)

num =int(input("Enter the number you want the factors of:"))

print_factors(num)

Output:
Enter the number you want the factors of:34
The factors of 34 are:
1
2
17
34

=== Code Execution Successful ===


Practical-33
Write a program to find the highest common multiple (HCF) or
greatest common divisor (GCD)

Code:
def compute_hcf(x, y):
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 hcf
num1 = int(input("Enter the first number:"))
num2 = int(input("Enter the second number:"))
print("The H.C.F. is", compute_hcf(num1, num2))

Output:
Enter the first number:34
Enter the second number:44
The H.C.F. is 2

=== Code Execution Successful ===


Practical-34
Write a program to sort words in alphabetical order

Code:
my_str = input("Enter a string: ")
words = [word.lower() for word in my_str.split()]

words.sort()

print("The sorted words are:")


for word in words:
print(word)

Output:
Enter a string: hi my name is shaurya
The sorted words are:
hi
is
my
name
shaurya

=== Code Execution Successful ===


Practical-35
Write a program to count the number of each vowel

Code:
string = input("Enter a string:")
vowels = "aeiouAEIOU"

count = sum(string.count(vowel) for vowel in vowels)


print(count)

Output:
Enter a string:shweta pagal hai
6

=== Code Execution Successful ===


Practical-36
Write a program to merge two dictionaries

Code:
d1 = {'a': 10, 'b': 8}
d2 = {'d': 6, 'c': 4}

d2.update(d1)
print(d2)

Output:
{'d': 6, 'c': 4, 'a': 10, 'b': 8}

=== Code Execution Successful ===


Practical-37
Write a program to access index of a list using for loop

Code:
my_list = [21, 44, 35, 11]

for index, val in enumerate(my_list):


print(index, val)

Output:
0 21
1 44
2 35
3 11
Practical-38
Write a program to iterate over dictionary using for loop

Code:
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

for key in dt:


print(key, dt[key])

Output:
a juice
b grill
c corn

=== Code Execution Successful ===


Practical-39
Write a program to sort a dictionary by value

Code:
d = {'ravi': 10, 'rajnish': 9, 'sanjeev': 15}

myKeys = list(d.keys())
myKeys.sort()

# Sorted Dictionary
sd = {i: d[i] for i in myKeys}
print(sd)

Output:
{'rajnish': 9, 'ravi': 10, 'sanjeev': 15}
Practical-40
Write a program to check if a key is already present in a
dictionary

Code:
my_dict = {1: 'a', 2: 'b', 3: 'c'}

if 2 in my_dict:
print("present")

Output:
present
Practical-41
Write a program to define and call a function

Code:
def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return

hello()

Output:
Enter your name: shaurya
Hello shaurya

=== Code Execution Successful ===


Practical-42
Write a program to show various arguments

1. Function argument

Code:
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
add_numbers(2, 3)
add_numbers(a = 2)
add_numbers()

Output:
Sum: 5
Sum: 10
Sum: 15

2. Keyword argument

Code:
def display_info(first_name, last_name):
print('First Name:', first_name)
print('Last Name:', last_name)
display_info(last_name = 'Cartman', first_name = 'Eric')
Output:
First Name: Eric
Last Name: Cartman

3. Arbitrary argument

Code:
# program to find sum of multiple numbers
def find_sum(*numbers):
result = 0
for num in numbers:
result = result + num
print("Sum = ", result)
# function call with 3 arguments
find_sum(1, 2, 3)
# function call with 2 arguments
find_sum(4, 9)

Output:
Sum = 6
Sum = 13
Practical-43
Write a program to print Fibonacci series using recursion

Code:
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = int(input("Enter number of terms:"))

if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i),end=”,”)

Output:
Enter number of terms:12
Fibonacci sequence:
0,1,1,2,3,5,8,13,21,34,55,89,

=== Code Execution Successful ===


Practical-44
Write a program to implement the following functions on
module:-

1. import standard math module


Code:
import math
print("The value of pi is", math.pi)

Output:
The value of pi is 3.141592653589793

2. import module by renaming it


Code:
import math as m
print(m.pi)

Output:
3.141592653589793

3. import only pi from math module


Code:
from math import pi
print(pi)
Output:
3.141592653589793

4. import all names from the standard module math


Code:
from math import *
print("The value of pi is", pi)

Output:
The value of pi is 3.141592653589793

5. dir function
Code:
print(dir(math))

Output:
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign',
'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial',
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf',
'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan',
'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan',
'tanh', 'tau', 'trunc', 'ulp']

=== Code Execution Successful === `


Practical-45
Write a program to implement random module in python

1) Seed()
Code:
import random
random.seed(1)
print(random.random())

Output:
0.13436424411240122

=== Code Execution Successful ===

2) Randrange()
Code:
import random
print("Random number between 0 - 100: ",end = "")
print(random.randrange(0,100))

Output:
Random number between 0 - 100: 96

=== Code Execution Successful ===


3) Randint()
Code:
import random
print("Random number between 0 - 100: ",end = "")
print(random.randint(0,100))

Output:
Random number between 0 - 100: 91

=== Code Execution Successful ===

4) Random()
Code:
import random
print(random.random())

Output:
0.8001251424508332

=== Code Execution Successful ===

5) Uniform()
Code:
import random
print("Random uniform n0. between 0 - 100: ",end = "")
print(random.uniform(0,100))
Output:
Random uniform n0. between 0 - 100: 47.774043396273505

=== Code Execution Successful ===

6) Shuffle()
Code:
import random
colors = ['Purple','Red','Blue','Green','Orange','Yellow']
print("Original List: ",colors)
random.shuffle(colors)
print("\nAfter Shuffling: ",colors)

Output:
Original List: ['Purple', 'Red', 'Blue', 'Green', 'Orange', 'Yellow']

After Shuffling: ['Orange', 'Green', 'Blue', 'Red', 'Purple', 'Yellow']

=== Code Execution Successful ===

You might also like