Python code for finding greatest among four numbers.
n1 = int(input("Enter 1st"))
n2 = int(input("Enter 2nd"))
n3 = int(input("Enter 3rd"))
n4 = int(input("Enter 4th"))
if n1 > n2 and n1>n3 and n1>n4:
print(f"{n1} is greatest")
elif n2>n1 and n2>n3 and n2>n4:
print(f"{n2} is greatest"
elif n3>n1 and n3>n2 and n3>n4:
print(f"{n3} is greatest")
else:
print(f"{n4} is greatest")
OR
list1 = []
num = int(input("Enter the no. of elements:"))
for i in range(1,num + 1):
elements = int(input("Enter the number"))
list1.append(elements)
print(f"Largest Number is:{max(list1)}")
Ex. Of command line argument
Cmdex.py:
import sys
x = int(sys.argv[1])
y = int(sys.argv[2])
sum = x + y
print(f"Addition of {x} and {y} is: {sum}")
py cmdex.py 7 3 (in terminal)
Addition of 7 and 3 is: 10
Ex. Of lambda function
x = lambda a,b: a*b
print(x(10,2))
Write python program to read contents of abc.txt and write same content to
pqr.txt.
with open("abc.txt","r") as f1:
file1 = f1.read()
print(file1)
with open("pqr.txt","w") as f2:
f2.writelines(file1)
with open("pqr.txt","r") as f2:
file2 = f2.read()
print(file2)
Design a Python program which will throw an exception if value entered by a
user is less than 0.
class NegativeValueError(Exception):
"Raised when negative value is entered"
pass
try:
num = int(input("Enter a number:"))
if num < 0:
raise NegativeValueError
else:
print(f"Number entered is: {num}")
except NegativeValueError:
print("Number entered is less than 0")
code to count frequency of each character in a given file.
import collections
import pprint
file_input = input("Enter file name:")
with open (file_input,"r") as f1:
count = collections.Counter(f1.read().upper())
pp = pprint.pformat(count)
print(pp)
Write a python program to read contents of one file and write same content to
another file.
fr = input("Enter file name:")
fw = input("Enter file name:")
with open (fr,"r") as f1:
file1 = f1.read()
print(file1)
with open (fw,"w") as f2:
f2.write(file1)
with open(fw,"r") as f3:
contents = f3.read()
print(contents)
WAP for importing module for addition and subtraction of 2 numbers.
add.py
def add(x,y):
return(x+y)
sub.py
def sub(x,y):
return(x-y)
main.py:
import add
import sub
print(f"Addition is {add.add(10,20)}")
print(f"Subtraction is {sub.sub(20,10)}")
WAP to perform following operations on tuples.
1. Create tuple
tuple1 = (1,2,3,4,5)
2. Access tuple element
for s in tuple1:
print(s)
OR
Print(“Elements:”tuple1[0])
3. Update tuple
Updating in tuple is not possible as tuples are immutable
4. Delete tuple
del tuple1
print(tuple1)
WAP to print factorial of a number using loop.
num = int(input("Enter a number:"))
factorial = 1
for i in range(1, num+1):
factorial *= i
print(f"factorial of {num} is {factorial}")
Using recursion:
n = int(input("Enter a number:"))
def fact(n):
if n == 0:
return 1
else:
return n*fact(n-1)
result = fact(n)
print(f"Factorial of {n} is: {result}")
WAP to check whether a number is prime or not.
num = int(input("Enter a number:"))
if num<2:
print("Not prime")
else:
for i in range(2,num):
if num%i == 0:
print(f"{num} is not prime")
break
else:
print(f"{num} is prime")
Write a program to create a dictionary of students that includes their ROLL NO.
and Names.
1. Add 3 students in the above dictionary.
stud_dict = {1:"Kraken",2:"Bing",3:"ecA"}
print(stud_dict)
2. Update name “Shreyas” of Roll no. 2.
stud_dict[2] = "Shreyas"
print(stud_dict)
3. Delete information of Roll No. 1.
del stud_dict[1]
print(stud_dict)
Program for Fibonacci series upto n terms
def fibonacci(x):
fib_series = [0,1]
while len(fib_series) < n :
next_term = fib_series[-1] + fib_series[-2]
fib_series.append(next_term)
return fib_series
n = int(input("Enter number:"))
result = fibonacci(n)
print(f"fibonacci upto {n} terms is:{result}")
Design a class student with data members; Name, roll number address. Create
suitable method for reading and printing students details.
class Student:
def getStudentDetails(self):
self.name = input("Enter Name:")
self.rollno = int(input("Enter roll no:"))
self.address = input("Enter Adresss")
def printStudentDetails(self):
print(self.name, self.rollno, self.address)
s1 = Student()
s1.getStudentDetails()
print("Student Details are:")
s1.printStudentDetails()
Create a parent class named Animals and a child class Herbivorous which will
extend the class Animal. In the child class Herbivorous over side the method
feed ( ).
class Animal:
def breathe(self):
print("I breathe oxygen")
def feed(self):
print("I eat food")
class Herbivores(Animal):
def feed(self):
print("I eat plants only, I am veg")
herbi = Herbivores()
herbi.feed()
herbi.breathe()
WAP to print the following:
1
1 2
1 2 3
1 2 3 4
rows = 4
for i in range(1, rows+1):
for j in range(1, i+1):
print(j, end=" ")
print()
2
468
10 12 14 16 18
num = 3
k=2
for i in range(1,num+1):
for j in range(i*2-1):
print(k,end = " ") [replace k with “*” to make It star patterns]
k = k+2
print()
1 2 3 4
2 3 4
3 4
4
for i in range(1,5):
for j in range(i,5):
print( j , end=" ") [replace j with “*” to make It star patterns]
print()
****
***
**
*
num = 4
for i in range(num,0,-1):
for j in range(0,num - i):
print(end=" ")
for j in range(0,i):
print("*", end=" ")
print()
Write a program to open a file in write mode and append some content at the end
of file
file1 = open("first.txt","w")
s = ("This is the some text\n","some more text\n")
file1.writelines(s)
file1.close()
file1 = open("first.txt","a")
file1.write("\n Some more appended text")
file1.close()
file1 = open("first.txt","r")
f = file1.read()
print(f)
Q]
T = (‘spam’, ‘Spam’, ‘SPAM!’, ‘SaPm’)
print (T [2] )
SPAM!
print (T [-2] )
SPAM!
print (T[2:] )
('SPAM!', 'SaPm')
print (List (T))
['spam', 'Spam', 'SPAM!', 'SaPm'] (this output if L in List(T) is in lowercase, maybe printing
mistake)
Write a program to create class EMPLOYEE with ID and NAME and display its
contents.
class employee:
def getdata(self,id,name):
self.id = id
self.name = name
def printData(self):
print("ID:", self.id)
print("Name:" , self.name)
e = employee()
e.getdata(107,"Jayesh")
e.printData()
Write down the output of the following Python code
>>>indices=['zero','one','two','three','four','five']
i)
>>>indices[:4]
['zero', 'one', 'two', 'three']
ii)
>>>indices[:-2]
['zero', 'one', 'two', 'three']
Write a python program to input any two tuples and interchange the tuple
variables.
t1 = tuple(input("Enter first number:"))
t2 = tuple(input("Enter second number:"))
print("Original tuples:")
print("Tuple 1:", t1)
print("Tuple 2:", t2)
t1, t2 = t2 ,t1
print("\nAfter interchanging:")
print("Tuple 1:", t1)
print("Tuple 2:", t2)
Write a Python Program to check if a string is palindrome or not.
a = input("Enter a string:")
a = a.lower()
b = a[-1::-1]
if(a == b):
print(f"{a} is palindrome")
else:
print(f"{a} is not palindrome")
Write a Python Program to check if a number is palindrome or not.
number = int(input("Enter a number:"))
temp = number
reverse = 0
while(number>0):
dig = number%10
reverse = reverse*10 + dig
number = number//10
if temp == reverse:
print(f"{temp} is a palindrome")
else:
print(f"{temp} is not a palindrome")
Write a Python program to calculate sum of digit of given number using function.
def sum_of_digits(num):
sum = 0
while(num > 0):
sum = sum + num%10
num = num//10
return sum
num = int(input("Enter a number:"))
s = sum_of_digits(num)
print(f"Sum of digits of {num} is: {s}")
Write a Python Program to accept values from user in a list and find the largest
number and smallest number in a list.
list1 = []
num = int(input("Enter no. of elements:"))
for i in range(1,num+1):
elements = int(input("Enter number:"))
list1.append(elements)
print(f"Largest number is:{max(list1)}")
print(f"Smallest number is:{min(list1)}")
Design a python program to calculate area of triangle and circle and print the
result
def triangle(base,height):
return 0.5* base* height
def circle(radius):
return 3.14* radius*radius
base = float(input("Enter base of the triangle:"))
height = float(input("Enter height of the triangle:"))
radius = float(input("Enter raidus of the circle:"))
triangle_area = triangle(base,height)
circle_area = circle(radius)
print(f"Area or triangle is: {triangle_area}")
print(f"Area of circle is: {circle_area}")
numpy ex:
import numpy as np
arr1 = np.array([1,2,3,4,5])
print(f"1D array: {arr1}")
arr2 = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(f"2D array: {arr2}")
print(f"Sum of 1D array: {np.sum(arr1)}")
print(f"Sum of 2D array: {np.sum(arr2)}")
print(f"Mean of 1D array: {np.mean(arr1)}")
print(f"Mean of 2D array: {np.mean(arr2)}")