0% found this document useful (0 votes)
22 views14 pages

1a.install Python and Set Up The Development Environment.: Code: Print ("Hello World") Output

Uploaded by

deepakguptaab321
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)
22 views14 pages

1a.install Python and Set Up The Development Environment.: Code: Print ("Hello World") Output

Uploaded by

deepakguptaab321
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/ 14

1a.Install python and set up the development environment.

After installing the setup adding it to path

1b. Write a python program to print Hello World.


Code :
print("Hello World")
Output:
1c. Write a program to calculate area of a circle.
Code :
from math import pi
r=float(input("Enter radius of the circle:”))
A= pi*r*r
print(“Area of the circle is “,A)
Output:

2a. Write a python program to check if a number is even or odd.


Code :
a=int(input("Enter the number : "))
if a%2==0:
print(f"{a} is a even number”)
else:
print(f"{a} is a odd number”)
Output :

2b. Write a python program to implement a simple calculator using conditional


statement.
Code :
while True:
print("What do you want to
perform?\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exit")
x=int(input("Enter Choice: "))
n1=float(input("Enter first number: "))
n2=float(input("Enter second number: "))
if(x==1):
print(f"{n1}+{n2}=",n1+n2)
elif(x==2):
print(f"{n1}-{n2}=",n1-n2)
elif(x==3):
print(f"{n1}×{n2}=",n1*n2)
elif(x==4):
print(f"{n1}/{n2}=",n1/n2)
elif(x==5):
break
else:
print("Enter a valid choice!!")
Output :

2c. Write a python program to print the Fibonacci series using for loop.
Code:
a=0
b=1
n=int(input("Enter number of elements: "))
print(f"Fibonacci series with {n} elements:",a,b,end=" ")
for i in range(0,n-2):
c=a+b
print(c,end=" ")
a=b
b=c
Output:

3a. Implement a function to check if a given string is Palindrome.


Code:
def pallindrome(s):
s1=s[::-1]
if (s==s1):
print(f"{s} is pallindrome.")
else:
print(f"{s} is not pallindrome.")
s=input("Enter string: ")
pallindrome(s)

Output:

3b. Perform various operation on list.


Code:
l=[]
n=int(input("Enter the no. of elements required in the list: "))
for i in range(1,n+1):
a=int(input(f"Enter element {i}: "))
l.append(a)
while True:
print("")
print(f"Original List: {l}")
print("Menu for list operations:\n1.Sorting in ascending order\n2.Sorting in descending
order\n3.Reversing a list\n4.Appending an element\n5.Slicing of list\n6.Exit")
ch=int(input("Enter choice:"))
if ch==1:
l.sort()
print(f"List sorted in ascending order: {l}")
elif ch==2:
l.sort()
l.reverse()
print(f"List sorted in descending order: {l}")
elif ch==3:
l.reverse()
print(f"List reversed: {l}")
elif ch==4:
a=int(input("Enter an element to append in the list: "))
l.append(a)
print(f"List after appending {a}: {l}")
elif ch==5:
a=int(input("Enter starting index: "))
b=int(input("Enter stopping index: "))
c=int(input("Enter step: "))
print(f"Sliced list: {l[a:b:c]}")
elif ch==6:
break
else:
print("Enter a valid choice")
Output:
3c. Write a python program use dictionaries to store and retrieve student grades.
Code:
a=int(input("Enter no. of students : "))
student_rec={}
for i in range(1,a+1):
name=input(“Enter student name:")
rollno=int(input(“Enter student roll no. :”))
grade=input("Enter grade: ")
student_rec[rollno]=[name,grade]
c=int(input("Enter rollno to search: ")
print(student_rec[c])
Output:

4a. Create a class to represent a book with attributes and methods.


Code:
class Book:
def __init__ (self, title, author, genre, publication_year):
self.title = title
self.author = author
self.genre = genre
self.publication_year= publication_year
def title(self):
return self.title
def author(self):
return self.author
def genre(self):
return self.genre
def publication_year(self):
return self.publication_year
def display_info(self):
return f"Title: {self.title}\nAuthor: {self.author}\nGenre:{self.genre}\nPublication Year:
{self.publication_year}\n"
book1 = Book("Verity", "Colleen Hoover", "Thriller",
2018)
book2 = Book("The Immortals of Meluha","Amish Tripathi","Fantasy Fiction",2010)
print(book1.display_info())
print(book2.display_info())

Output:

4b. Write a python program to implement inheritance in the above class .


Code:
class Book:
def __init__ (self, title, author, genre, publication_year):
self.title = title
self.author = author
self.genre = genre
self.publication_year= publication_year
def title(self):
return self.title
def author(self):
return self.author
def genre(self):
return self.genre
def publication_year(self):
return self.publication_year
def display_info(self):
return f"Title: {self.title}\nAuthor: {self.author}\nGenre:{self.genre}\nPublication Year:
{self.publication_year}\n"

class EBook(Book):
def __init__(self, title, author, genre, price, file_size,file_format):
super().__init__(title, author, genre, price)
self.file_size = file_size
self.file_format = file_format
def file_size(self):
return self.file_size
def file_format(self):
return self.file_format
def display_file_info(self):
return f"File Size: {self.file_size}MB\nFile Format:{self.file_format}"
def display_info(self):
book_info = super().display_info()
return book_info + f"\n{self.display_file_info()}"
ebook1 = EBook("Verity", "Colleen Hoover", "Thriller",2018, 15,
"PDF")
print(ebook1.display_info())

Output:

4c. Write a python program to implement a generator function to generate the


fibonacci sequence.
Code:
def fibonacci_generator(n):
a,b=0,1
print(a,b,end=" ")
for i in range(n-2):
c=a+b
print(c,end=" ")
a=b
b=c
n=int(input("How many fibonacci numbers you want to print?"))
fibonacci_generator(n)

Output:

5a. Use lambda functions, map, and filter to perform operations on a list.
Code:
num= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original list: ",num)
square_num = list(map(lambda x: x**2, num))
print("Squared Numbers:", square_num)
even_num = list(filter(lambda x: x % 2 == 0, num))
print("Even Numbers:", even_num)

Output:

5a. Create a module that contains functions for mathematical operations.


Code:
def add(a, b):
return a + b
def subtract(a, b):
return a – b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
print("Cannot divide by zero!")
return a / b

import mathopsmodule as mo
a = 10
b=5
print(mo.add(a, b)) #output: 15
print(mo.subtract(a, b)) #output: 5
print(mo.multiply(a, b)) #output: 50
print(mo.divide(a, b)) #output:2.0

6a. Create and manipulate NumPy arrays.


Code:
import numpy as np
arr1=np.array([11,12,13])
arr2=np.array([[11,12,13],[14,15,16]])

row=arr2[0,:] #Accessing and Manipulating Arrays


col=arr2[:,1]

add=arr1+5 #Element-wise operations


multiply=arr1*2
sum_arr=arr1+arr1
product=arr1*arr1

reshape=arr1.reshape(3,1) #Reshape
max_val=arr1.max() #Statistics
min_val=arr1.min()
mean=arr1.mean()
median=np.median(arr1)
std_dev=arr1.std()

print("Original Array:")
print(arr1)
print("\nOriginal Matrix:")
print(arr2)
print("\nAccessing and Slicing:")
print("First Row:",row)
print("Second Column:",col)
print("\nElementwise Operation:")
print("arr1+5 =",add)
print("arr1*2 =",multiply)
print("\nElement wise operation between arrays:")
print("arr1+arr1 =",sum_arr)
print("arr1*arr1 =",product)
print("\nReshaped Array:\n",reshape)
print("\nStatistics")
print("Max Value:",max_val)
print("Min Value:",min_val)
print("Mean:",mean)
print("Median:",median)
print("Standard Deviation:",std_dev)
Output:
6b. Perform basic operations and indexing on arrays.
Code:
import numpy as np
arr=np.array([1,2,3,4,5,6,7,8,9])
print("Original Array:",arr)
print("Element at index 0:",arr[0])
print('Element at index 3:',arr[3])
sliced_arr=arr[1:5]
print("Sliced Array:",sliced_arr)

arr1=np.array([1,2,3])
arr2=np.array([4,5,6])
print("First array:",arr1,"\nSecond array:",arr2)
add=arr1+arr2
subtract=arr2-arr1
product=arr1*arr2
division=arr2/arr1
print("Addition Result:",add)
print("Subraction Result:",subtract)
print("Multiplication Result:",product)
print("Division Result:",division)

Output:

7a. Implement string operations.


Code:
import numpy as np
str_arr=np.array(["Delhi","Mumbai","Chennai","Gurugram","Bangalore"])
concatenated_str=np.char.add(str_arr,"is a city")
print("Concatenated Array:",concatenated_str)
split_arr=np.char.split(str_arr,'e')
print("Split Array:",split_arr)
upper=np.char.upper(str_arr)
print("Uppercase Array:",upper)
lower=np.char.lower(str_arr)
print("Lowercase Array:",lower)
count=np.char.count(str_arr,'a')
print("count of'e' in each string",count)

Output:

7b. Use regular expressions to validate email addresses.


Code:
import re
def valid_email(email):
pattern=r'^[\w\.-]+@[\w\.-]+\.\w+'
if re.match(pattern,email):
return True
else:
return False
email1="[email protected]"
email2="yahoo-mail"
email3="unknown@comdot."
print("Email 1 is valid:",valid_email(email1))
print("Email 2 is valid:",valid_email(email2))
print("Email 3 is valid:",valid_email(email3))

Output:

8a. Read data from a text file and perform operations.


Code:
ob= open('poem.txt','r')
s=ob.read()
vow=con=upper=lower=0
for i in s:
if(i.isalpha() and i in 'aeiouAEIOU'):
vow=vow+1
elif(i.isalpha() and i not in 'aeiouAEIOU'):
con=con+1
for i in s:
if(i.isupper()):
upper=upper+1
elif(i.islower()):
lower=lower+1
print("No. of vowels:",vow)
print("No. of consonants:",con)
print("No. of uppercase characters:",upper)
print("No. of lowercase characters:",lower)

Output:

8b. Handle exceptions for file operations and input validations.


Code:
try:
ob=open("file.txt",'r')
num=ob.read()
print("Data read from file",num)
sum_of_num=sum(num)
average=sum_of_num/len(num)
max_val=max(num)
min_val=mim(num)
print("Sum of Numbers:",sum_of_num)
print("Average:",average)
print("Maximum value:",max_val)
print("Minimum value:",min_val)

except FileNotFoundError:
print("!!File not found. Please check the file path!!")
except ValueError:
print("!!Invalid data in the file!!")
except ZeroDivisionError:
print("Cannot calculate the average with no data!!")
except Exception as e:
print("An unexpected error occured",str(e))
Output:

You might also like