0% found this document useful (0 votes)
9 views

python_lab_A_B

The document contains various Python programming exercises covering topics such as Fibonacci sequence checking, solving quadratic equations, summing natural numbers, and displaying multiplication tables. It also includes examples of searching algorithms, calculator functions, string manipulations, sorting algorithms, file operations, regular expressions, data structures like lists and dictionaries, GUI creation with Tkinter, exception handling, and data visualization using Matplotlib. Each section provides code snippets, expected outputs, and explanations for better understanding.

Uploaded by

prashobh1719
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)
9 views

python_lab_A_B

The document contains various Python programming exercises covering topics such as Fibonacci sequence checking, solving quadratic equations, summing natural numbers, and displaying multiplication tables. It also includes examples of searching algorithms, calculator functions, string manipulations, sorting algorithms, file operations, regular expressions, data structures like lists and dictionaries, GUI creation with Tkinter, exception handling, and data visualization using Matplotlib. Each section provides code snippets, expected outputs, and explanations for better understanding.

Uploaded by

prashobh1719
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/ 13

Python Part A

1. Check if a number belongs to the Fibonacci Sequence

N = int(input("Enter the number you want to check: "))


f1 = 0
f2 = 1
f3 = 0
if (N == 0 or N == 1):
print(f"Given number {N} is Fibonacci number")
else:
while f3 < N:
f3 = f1 + f2
f1 = f2
f2 =f3
if f3==N:
print(f"Given number {N} is fibonacci number")
else:
print(f"Given number {N} is not a fibonacci number")

Output
Enter the number you want to check: 4
Given number 4 is not a fibonacci number
Enter the number you want to check: 5
Given number 5 is fibonacci number

2. Solve Quadratic Equation

import math
a = int(input('Enter a:'))
b = int(input('Enter b:'))
c=int(input('Enter C:'))
dis=b*b-4*a*c
sqrt_dis=math.sqrt(abs(dis))
if dis > 0:
print(" Real and different roots are : ")4
print((-b + sqrt_dis) / (2*a))
print((-b - sqrt_dis) / (2 * a))
elif dis==0:
print(" Real and same roots are: ")
print(-b / (2 * a))
else:
print("Complex Roots are : ")
print(- b / (2 * a), " + ", sqrt_dis, "j")
print(- b / (2 * a), " - ", sqrt_dis, "j")

output
Enter a:1
Enter b:2
Enter C:3
Complex Roots are :
-1.0 + 2.8284271247461903 j
-1.0 - 2.8284271247461903 j

3. Find the sum of n natural numbers

N = int(input('Enter a number: '))


sum = 0
x = 1
while x <= N:
sum = sum + x
x = x + 1
print(f" The sum of {N} natural numbers = {sum}")

Output
Enter a number: 5
The sum of 5 natural numbers = 15

4. Display Multiplication Tables

num = int(input('Display multiplication table of: '))


for i in range(1, 11):
print ("%d * %d = %d" % (num, i, num * i))

output

Display multiplication table of: 13


13 * 1 = 13
13 * 2 = 26
13 * 3 = 39
13 * 4 = 52
13 * 5 = 65
13 * 6 = 78
13 * 7 = 91
13 * 8 = 104
13 * 9 = 117
13 * 10 = 130

5. Check if a given number is a Prime Number or not

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


flag =True
if num ==1:
print(num, "is not a prime number")
elif num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = False
break
if flag == True:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Output

Enter a number: 6
6 is not a prime number

Enter a number: 3
3 is a prime number

6. Implement a sequential search

from array import *


def SequentialSearch(arr, key):
for i in range(len(arr)):
if (arr[i] == key):
return i
return -1
arr_ele = array('i',[10, 20, 30, 40, 50])
print("Elements of the array are :")
for x in arr_ele :
print(x)
key = int(input('Enter number to be searched : '))
index = SequantialSearch(arr_ele, key)
if(index == -1):
print(key, 'not Found')
else:
print(key, 'Found at Index', (index+1))

Output

Elements of the array


are : 10
20
30
40
50
Enter number to be searched :
2020 Found at Index 2

Elements of the array


are : 10
20
30
40
50
Enter number to be searched :
9090 not Found

7. Create a calculator program


def add(x, y):
return (x + y)
def subtract(x, y):
return (x - y)
def multiply(x, y):
return (x * y)
def divide(x, y):
return (x / y)
print("Enter two numbers ")
num1 = float(input("Enter first number : "))
num2 = float(input("Enter second number : "))
print("Select operation : ")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
while True:
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid Input !")
break
Output
Enter two numbers
Enter first number : 6
Enter second number : 2
Select operation :
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4): 1
6.0 + 2.0 = 8.0
Enter choice(1/2/3/4): 2
6.0 - 2.0 = 4.0
Enter choice(1/2/3/4): 3
6.0 * 2.0 = 12.0
Enter choice(1/2/3/4): 4
6.0 / 2.0 = 3.0
8. Explore string functions

str="Python is powerful programming language."


print("Given string :",str)
print("String in Uppercase:",str.upper())
print("string in lowercase:",str.lower())
print("check if the given string starts with character
'P':",str.startswith('P'))
print("check if the given string ends with string
'Powerful':",str.endswith("Powerful"))
print("Count of character'g' in the given string:",str.count('g'))
print("String with each word in uppercase:",str.title())
print("String with each word in upper and lowercase
swapped:",str.swapcase())
print("Find occurrence of sub string'Language' in the given
string:",str.find('Language'))
print("String after replacement of string 'powerful' by 'high
level':",str.replace("powerful","high level"))
print("string splitting:",str.split(","))
print("string after joining:","".join([str,"and portable"]))

output
Given string : Python is powerful programming language.
String in Uppercase: PYTHON IS POWERFUL PROGRAMMING LANGUAGE.
string in lowercase: python is powerful programming
language.check if the given string starts with character 'P':
True
check if the given string ends with string 'Powerful':
FalseCount of character'g' in the given string: 4
String with each word in uppercase: Python Is Powerful Programming Language.
String with each word in upper and lowercase swapped: pYTHON IS
POWERFULPROGRAMMING LANGUAGE.
Find occurrence of sub string'Language' in the given string: -1
String after replacement of string 'powerful' by 'high level': Python is high level
programminglanguage.
string splitting: ['Python is powerful programming language.']
string after joining: Python is powerful programming language.and portable

9. Implement Selection sort


def selectionSort(array, size):
for ind in range(size):
min_index = ind

for j in range(ind + 1, size):


# select the minimum element in every iteration
if array[j] < array[min_index]:
min_index = j
# swapping the elements to sort the array
(array[ind], array[min_index]) = (array[min_index], array[ind])

arr = [11, 9, 8, 7, 2, 74]


size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)

output
The array after sorting in Ascending Order by selection sort is:

[2, 7, 8, 9, 11, 74]


11. Read and write into a file

file_path="example.txt"
def write_to_file(file_path,content):
with open(file_path,'w') as file:
file.write(content)
print("content written to the file succesfully!")
def read_from_file(file_path):
with open(file_path,'r') as file:
content=file.read()
print("content read from the file succesfully!")
print(content)
write_to_file(file_path,"hello")
read_from_file(file_path)
PART B
1. Demonstrate use of basic regular expression
import re
str="Python Programming"
x=re.findall("Program",str)
print(x)
x=re.findall("y",str)
print(x)
x=re.findall("ing",str)
print(x)
x=re.search("Programming",str)
print(x)
print(x.span())
print(x.start())
print(x.end())
print(x.group())
x=re.split(" ",str)
print(x)
x=re.sub("\s","$",str)
print(x)

Output

['Program']
['y']
['ing']
<re.Match object; span=(7, 18),
match='Programming'> (7, 18)
7
18
Programming
['Python',
'Programming']
Python$Programming

2. Demonstrate use of advanced regular expression for data validation

import re
if name ==' main ':
def validate_email(email:bool):
regex=re.compile('^[a-z0-9]+[\\.\_]?[a-z0-9]+[@]\w+[.]\w{2,3}$')
matchobj=re.search(regex,email)
asbool=bool(matchobj)
return asbool
my_email=input("Enter an email address")
res=validate_email(my_email)
if res==True:
print("Email is valid")
else:
print("Email is not valid")
Output
Enter an email address:
[email protected]
Email is valid

Enter an email address


12
Email is not valid

3. Demonstrate use of list

name=[]
marks=[]
for i in range(5):
n=input("Enter student name")
m=int(input("Enter marks of student"))
name.append(n)
marks.append(m)
high=max(marks)
low=min(marks)
print("Highest marks is",high)
print("Lowest marks is",low)
for i in range(5):
if high==marks[i]:
print("Student having highest marks is",name[i])
if low==marks[i]:
print("Student having lowest marks is",name[i])

Output
Enter student name:
Arun Enter marks of
student: 76 Enter student
name: Arav Enter marks
of student: 69 Enter
student name: Astha
Enter marks of student:
82 Enter student name:
Briti Enter marks of
student: 86
Enter student name: Manthhan
Enter marks of student: 85

Highest marks is 86
Lowest marks is 69
Student having lowest marks is Arav
Student having highest marks is Briti
4. Demonstrate use of dictionary

num=int(input("Enter the number of employees"))


employee=dict()
for count in range(num):
name=input("Enter the name of employee:")
salary=int(input("enter the salary:"))
employee[name]=salary
print("\n Employee_name\tSalary")
for k in employee:
print(k,'\t\t',employee[k])

Enter the number of employees 3


Enter the name of employee: Kaashvi
enter the salary:12000
Enter the name of employee: Samarth
enter the salary:14000
Enter the name of employee:Ashwin
enter the salary:11500

Employee_name Salary
Kaashvi 12000
Samarth 14000
Ashwin 11500

5. Create a GUI using Tkinter module

import time
from tkinter import *
canvas = Tk()
canvas.title("Digital Clock")
canvas.geometry("350x200")
canvas.resizable(1,1)
label = Label(canvas, font=("Courier", 30, 'bold'), bg="blue", fg="white",
bd =30)
label.grid(row =0, column=1)
def digitalclock():
text_input = time.strftime("%H:%M:%S")
label.config(text=text_input)
label.after(200, digitalclock)
digitalclock()
canvas.mainloop()

6. Demonstrate exceptions in python

try:
a = int(input("Enter value for a"))
b = int(input("Enter value for b"))
print(a / b)
age = int(input("How old are you?"))
print(f"You are {age} years old")
print("Select your favroite fruit")
list=["Apple","Cherry","Mango"]
print(list[1])
except ZeroDivisionError:
print('Division by zero not allowed')
except ValueError:
print("Invalid age was entered")
except IndexError:
print("Invalid index was used for the list")
except:
print("some other exception occured")
finally:
print("End of program")

Output

Enter value for a:10


Enter value for b:0
Division by zero not allowed
End of program

Enter value for a:10


Enter value for b:5
2.0
How old are you?
g
Invalid age was entered
End of program

Enter value for a: 6


Enter value for b:3
2.0
How old are you? 20
You are 20 years old
Select your favourite fruit
Invalid index was used for the list
End of program

Enter value for a: 6


Enter value for b:3
2.0
How old are you? 20
You are 20 years old
Select your favourite fruit
Invalid index was used for the list
End of program
7. Drawing Line chart and Bar chart using Matplotlib

import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]


plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(dict(data=[2, 4, 1, 5, 9, 6, 0, 7]))
fig, ax = plt.subplots()

df['data'].plot(kind='bar', color='red')
df['data'].plot(kind='line', marker='*', color='black', ms=10)

plt.show()

8. Drawing Histogram and Pie chart using Matplotlib


import matplotlib.pyplot as plt
data = [5, 10, 12, 8, 7, 3, 5, 2, 7, 9, 6, 4, 5, 3, 6, 7, 8, 10]
labels = ['Proteins', 'Vegetables', 'Grains', 'Vitamins']
sizes = [30, 25, 20, 15]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
ax1.hist(data, bins=10, color='#66b3ff', edgecolor='black')
ax1.set_title('Data Distribution')
ax2.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%',
startangle=90)
ax2.set_title('Diet Distribution')
plt.subplots_adjust(wspace=0.4)
plt.show()
9. Create array using Numpy and perform operations on array

import numpy as np

# Initializing the array

arr = np.array([7,16, 25])


arr1 = np.array([4,8,6])

print('First array:')
print(arr)

print('\nSecond array:')
print(arr1)

print('\nAdding the twoarrays:')


print(np.add(arr, arr1))

print('\nSubtracting the two arrays:')


print(np.subtract(arr, arr1))

print('\nMultiplying the two arrays:')


print(np.multiply(arr, arr1))

print('\nDividing the two arrays:')


print(np.divide(arr, arr1))

print('\n mod of two arrays:')


print(np.mod(arr,arr1))

print("\n power for array")


print(np.power(arr,2))
Output

First array:

[ 7 16 25]

Second array:

[4 8 6]

Adding the two

arrays: [11 24 31]

Subtracting the two

arrays: [ 3 8 19]

Multiplying the two

arrays: [ 28 128 150]

Dividing the two arrays:

[1.75 24.16666667]

mod of two arrays:

[3 0 1]

power for

array [ 49 256

625]

You might also like