Python Practical File Final
Python Practical File Final
Code:
print("Hello World!")
Output:
Hello World!
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:
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:
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:
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:
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
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)
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)
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:
import random
a= random.randint(1,100)
print(a)
Output:
81
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:
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:
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:
a=int(input("Enter a number A:"))
b=int(input("Enter a number B:"))
c=int(input("Enter a number C:"))
Output:
Enter a number A:23
Enter a number B:33
Enter a number C:44
C is the largest number
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:
lower=int(input("Enter the lowest value for the interval:"))
upper=int(input("Enter the highest value for the interval:"))
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:
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:
n=int(input("Enter length of the series:"))
num1 = 0
num2 = 1
next_number = num2
count = 1
Output:
Enter length of the series:6
1 2 3 5 8 13
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:
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:"))
Output:
find sum of all natural numbers till:4
The sum is 6
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:
list1=[]
if(len(list1)==0):
print("The list is empty")
else:
print("The list is not empty")
Output:
The list is empty
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:
list1=["hi","bye",1,2,3,"hehe"]
print("inputed list:",list1)
Output:
inputed list: ['hi', 'bye', 1, 2, 3, 'hehe']
Last element of the input list = hehe
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:
import calendar
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:
dec = int(input("Enter a decimal value:"))
Output:
Enter a decimal value:344
The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.
Code:
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
print_factors(num)
Output:
Enter the number you want the factors of:34
The factors of 34 are:
1
2
17
34
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:
my_str = input("Enter a string: ")
words = [word.lower() for word in my_str.split()]
words.sort()
Output:
Enter a string: hi my name is shaurya
The sorted words are:
hi
is
my
name
shaurya
Code:
string = input("Enter a string:")
vowels = "aeiouAEIOU"
Output:
Enter a string:shweta pagal hai
6
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:
my_list = [21, 44, 35, 11]
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'}
Output:
a juice
b grill
c corn
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
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))
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,
Output:
The value of pi is 3.141592653589793
Output:
3.141592653589793
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']
1) Seed()
Code:
import random
random.seed(1)
print(random.random())
Output:
0.13436424411240122
2) Randrange()
Code:
import random
print("Random number between 0 - 100: ",end = "")
print(random.randrange(0,100))
Output:
Random number between 0 - 100: 96
Output:
Random number between 0 - 100: 91
4) Random()
Code:
import random
print(random.random())
Output:
0.8001251424508332
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
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']