Abhijit_python
PART -A
Program 1: Check whether the number is belongs to Fibonacci series or not.
n=int(input("Enter a number:")) c=0
a=1 b=1
if n==0 or n==1:
print("yes,It is Fibonacci Number") else:
while c<n: c=a+b b=a
a=c if c==n:
print("Yes,{0} is fibonacci number".format(n)) else:
print("No,{0} is not fibonacci number".format(n))
=========OUTPUT======== Ex:1
Enter a number:5
Yes,5 is fibonacci number
Ex:2
Enter a number:4
No,4 is not fibonacci number
Program 2: Solve Quadratic Equations
import cmath
a=int(input("Enter value for a:")) b=int(input("Enter value for b:")) c=int(input("Enter value for 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:\n",sol1,"and",sol2)
=========OUTPUT========
Enter value for a:5 Enter value for b:10 Enter value for c:15 the solution are:
(-1-1.4142135623730951j) and (-1+1.4142135623730951j)
Program 3:Find the sum of natural numbers
num=int(input("Enter a number:")) if num<0:
print("Enter a positive number:") else:
sum=0 while(num>0):
sum+=num num-=1
print("the sum is:",sum)
=========OUTPUT========
Enter a number:9 the sum is: 45
Program 4: Display Multiplication table
num=int(input("Display Multiplication Table of :")) for i in range(1,11):
print(num,'x',i,'=',num*i)
=========OUTPUT========
Display Multiplication Table of :6 6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Program 5: To check if a number is prime or not
num = int(input("Enter a number: "))
i = 2
flage = False
if num == 1 or num == 0: print("not a prime")
else:
for i in range(2, num): if num % i == 0:
flage = True break
if flage == True:
print("Not a prime number") else:
print("Prime number")
=========OUTPUT======== Ex:1
Enter a number: 8 Not a prime number Ex:2
Enter a number: 3 Prime number
Program 6: Implement sequent search
def lin_search(list,n,key): for i in range(0,n):
if(list[i]==key): return i
return-1
n=int(input("Enter the size:")) list1=input("Enter the number:").split() list1=[int(x)for x in list1]
key=int(input("Entern the key element to searched:")) n=len(list1)
res=lin_search(list1,n,key) if(res==-1):
print("element not found") else:
print("element found at index:",res)
=========OUTPUT======== Ex:1
Enter the size:4
Enter the number: 10 20 30 30
Entern the key element to searched:20 element found at index: 1
Ex:2
Enter the size:5
Enter the number:2 5 9 12 3
Entern the key element to searched:12 element found at index: 3
Program 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): if y!=0:
return x/y else:
return"error! division by zero.>" 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 in ('1','2','3','4'):
try:
num1=float(input("Enter first number:")) num2=float(input("Enter second number:"))
except ValueError:
print("invalid input please Enter a number") continue
if choice=='1':
print(f"{num1}+{num2}={add(num1,num2)}") elif choice=='2':
print(f"{num1}-{num2}={substract(num1,num2)}") elif choice=='3':
print(f"{num1}*{num2}={multiply(num1,num2)}") elif choice=='4':
print(f"{num1}/{num2}={divide(num1,num2)}")
next_calculation=input("let's do the next calcutlation?(yes/no):").lower() if next_calculation=="no":
break else:
print("invalid input .please select a valid option.")
=========OUTPUT========
select operation.
1.add 2.subtract 3.multiply 4.divide
Enter choice(1/2/3/4): 1 Enter first number: 10 Enter second number: 20 10.0+20.0=30.0
let's do the next calcutlation?(yes/no):yes Enter choice(1/2/3/4): 3
Enter first number: 10 Enter second number: 2 10.0*2.0= 20.0
let's do the next calcutlation?(yes/no):
Program 8: Exploren string function
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
print("Conversion of uppercase of", str1, "is", str1.upper()) print("Conversion of lowercase of", str2, "is", str2.lower()) print("Swapcase of string", str1, "is", str1.swapcase()) print("Title case of string", str1, "is", str1.title())
print("String replacement of first string", str1, "is", str1.replace(str1, str2)) string = "python is awesome"
capitalized_string = string.capitalize() print("Old string:", string)
print("Capitalized string:", capitalized_string) name = "bcacollegenidasoshi"
if name.isalpha() == True:
print("All characters are alphabets") else:
print("All characters are not alphabets") print("Maximum is", max(1, 2, 3, 4))
num = [1, 3, 2, 8, 5, 10, 6]
print("Maximum number is:", max(num)) teststring = "python"
print("Length of", teststring, "is", len(teststring))
=========OUTPUT========
Enter the first string: Mahesh
Enter the second string: Gayakwad
Conversion of uppercase of Mahesh is MAHESH Conversion of lowercase of Gayakwad is gayakwad Swapcase of string Mahesh is mAHESH
Title case of string Mahesh is Mahesh
String replacement of first string Mahesh is Gayakwad Old string: python is awesome
Capitalized string: Python is awesome All characters are alphabets Maximum is 4
Maximum number is: 10 Length of python is 6
Program 9: To implement selection sort
array=[]
print("Enter the limit") n=int(input())
for i in range(n):
element=int (input("Enter the element:")) array.append(element)
for i in range(n-1): min=i
for j in range (i+1,n):
if array[min]>array[j]: min=j
if min!=i:
temp=array[i]
array[i]=array[min] array[min]=temp
print("the sorted array ub ascending order :",end='\n') for i in range(n):
print(array[i])
=========OUTPUT========
Enter the limit 5
Enter the element:12 Enter the element:2 Enter the element:5 Enter the element:23 Enter the element:1
the sorted array ub ascending order : 1
5
2
12
23
Program 10: To Implement stack
#initial empty stack stack=[]
#append() function to push #element in the stack
stack.append('1') stack.append('2') stack.append('3') print(stack)
#pop()function to pop #element from stack in #LIFO order
print('\n element poped fromo my_stack') print(stack.pop())
print(stack.pop()) print(stack.pop()) #print(stack.pop())
print('\n my_stack after element are poped:') print(stack)
=========OUTPUT========
['1', '2', '3']
element poped fromo my_stack 3
2
1
my_stack after element are poped: []
Program 11: Road and Write into a file
#open a file for writing
file-open("E:\klcF.txt","w")
#write some text to the file
file.write("Welcome to BCA Department\n")
L= ['This is BCA College \n', 'Place is Nidasoshi \n', 'Fourth semester \n' file.writelines(L)
#close the file file.close()
#open the file for reading file=open("E:\klcF.txt","r")
#read the contents of the file into a string variable file_cont-file.read()
#print the contents of the file print(file_cont)
=========OUTPUT========
E:\kleF.txt
Welcome ot BCA Department This is BCA College
Place is Nidasoshi Fourth Semester
PART B
Program 1: Demonstrate usage of basic regular expression
import re
# Search String
str = "The rain in spain"
x = re.findall("ai", str)
print("Search of string 'ai': ", x)
x = re.search("\s", str)
print("The first white-space character is located in position: ", x.start())
x = re.split("\s", str, maxsplit=1) # Fixed positional argument issue print("Split the string in the occurrence of first white-space:", x)
x = re.sub("\s", "9", str)
print("Each white-space is replaced with 9 digit: ", x) print("---")
# Metacharacters
x = re.findall("[a-g]", str)
print("The letters in between a to g in the string:", x)
x = re.findall("spain$", str) if x:
print("\n", str, ": Yes, this string ends with 'spain' word ") else:
print("\n No match ")
x = re.findall("^The", str) if x:
print("\n", str, ": Yes, this string starts with 'The' word") else:
print("\n No match ")
str1 = "The rain in spain falls mainly in the plain" x = re.findall("ai*", str1)
print("\n All ai matching characters:", x) if x:
print("Yes, there is at least one match") else:
print("No match")
x = re.findall("all{1}", str1)
print("In the string which contains 'all':", x) if x:
print("Yes, there is at least one match") else:
print("No match")
str2 = "That will be 59 dollars" x = re.findall("\d", str2)
print("\n Digits in the string:", x)
x = re.findall("do...rs", str2)
print("\n Dot metacharacter matches any character:", x)
=========OUTPUT========
Search of string 'ai': ['ai', 'ai']
The first white-space character is located in position: 3
Split the string in the occurrence of first white-space: ['The', 'rain in spain'] Each white-space is replaced with 9 digit: The9rain9in9spain
--------------------------------------------------------------------------------
The letters in between a to g in the string: ['e', 'a', 'a'] The rain in spain : Yes, this string ends with 'spain' word The rain in spain : Yes, this string starts with 'The' word All ai matching characters: ['ai', 'ai', 'a', 'ai', 'ai']
Yes, there is at least one match
In the string which contains 'all': ['all'] Yes, there is at least one match
Digits in the string: ['5', '9']
Dot metacharacter matches any character: ['dollars']
Program 2: Demonstrate use of advanced regular expression for – data validation.
import re
p=input("enter your password:") x=True
while x:
if(len(p)<6 or len(p)>20): break
elif not re.search("[a-z]",p): break
elif not re.search("[A-Z]",p): break
elif not re.search("[0-9]",p): break
elif not re.search("[$#@]",p): break
elif re.search("\s",p): break
else:
print("valid password") x=False
break
if x:
print("Invalid password")
=========OUTPUT========
Ex:1 enter your password:Mahesh@123 valid password
Ex:2 enter your password:Mahesh@# Invalid password
Program 3: Demonstrate use of List
print("PROGRAM FOR BUILT-IN METHODS OF LIST\n") number=[1,2,13,40,5]
print(number)
sum_of_number=sum(number) print("Sum=",sum_of_number) max_number=max(number) print("max=",max_number) min_number=min(number) print("min=",min_number) number.sort()
print("sorted number in ascending ",number) number.reverse()
print("sorted number in descending",number) number.append(6)
print("updated number",number) number.remove(13)
print("removed",number) number.clear()
print("list after clear",number)
=========OUTPUT========
PROGRAM FOR BUILT-IN METHODS OF LIST [1, 2, 13, 40, 5]
Sum= 61
max= 40
min= 1
sorted number in ascending [1, 2, 5, 13, 40]
sorted number in descending [40, 13, 5, 2, 1]
updated number [40, 13, 5, 2, 1, 6]
removed [40, 5, 2, 1, 6] list after clear []
Program 4: Demonstrate use of Dictionaries
person={"name":"amit","age":"21","city":"bengaluru","occupation":"student"} print(person["name"])
print(person["age"]) print(person["city"])
print(person["occupation"]) person["age"]=25
person["occupation"]="engineer" print(person)
person["country"]="India" print(person)
del person["city"] print(person)
if"occupation"in person:
print("occupation:",person["occupation"])
=========OUTPUT========
amit 21
bengaluru student
{'name': 'amit', 'age': 25, 'city': 'bengaluru', 'occupation': 'engineer'}
{'name': 'amit', 'age': 25, 'city': 'bengaluru', 'occupation': 'engineer', 'country': 'India'}
{'name': 'amit', 'age': 25, 'occupation': 'engineer', 'country': 'India'} occupation: engineer
Program 5: Create SQlite Database and perform operations on tables
import sqlite3
conn=sqlite3.connect('text.db') cursor=conn.cursor()
cursor.execute("create table emp11(id integer,name text)") cursor.execute("insert into emp11(id,name)values(101,'ravi')") cursor.execute("insert into emp11(id,name)values(102,'raj')")
cursor.execute("insert into emp11(id,name)values(103,'ramesh')") print("\n displaying the emp11 table")
cursor.execute("select *from emp10") rows=cursor.fetchall()
for row in rows: print(row)
print("\n after update and delete the records in the table")
cursor.execute("update emp11 set name='Akash' where id=101") cursor.execute("delete from emp11 where id=103")
print ("displaying the emp11 table") cursor.execute("select * from emp11") rows=cursor.fetchall()
for row in rows:
print(row)
print("\n table is droped...")
cursor.execute("drop table emp11") conn.commit()
cursor.close() conn.close()
=========OUTPUT========
displaying the emp11 table
after update and delete the records in the table displaying the emp11 table
(101, 'Akash')
(102, 'raj')
table is droped...
Program 6: Create a GUI using Tkinter module
import tkinter as tk
from tkinter import messagebox def show_message():
messagebox.showinfo("Hello", "Welcome to the GUI") window = tk.Tk()
window.title("My GUI") window.geometry("300x200")
label = tk.Label(window, text="Hello, world") label.pack()
button = tk.Button(window, text="Click me", command=show_message) button.pack()
window.mainloop()
=========OUTPUT========
Program 7: Demonstrate exception in python
try:
num1=int(input("enter the number:"))
num2=int(input("enter the denominator:")) result=num1/num2
print("result:",result) except ValueError:
print("Invalid input") except ZeroDivisionError:
print("connot divide by zero") else:
print("no exception occur") finally:
print("end of program")
=========OUTPUT========
Ex:1
enter the number:10 enter the denominator:0 connot divide by zero end of program
Ex:2
enter the number:12.2 Invalid input
end of program
Program 8: Drawing Line chart and Bar chart using Matplotlib
import matplotlib.pyplot as plt #Data
x=[2,3,4,6,8]
y=[2,3,4,6,8]
plt.subplot(121)
plt.plot(x,y,color='tab:red')
plt.title('Line Chart')
plt.xlabel('X axis label') plt.ylabel('Y axis label') plt.subplot(122)
plt.title('Bar chart')
plt.xlabel('X axis label') plt.ylabel('Y axis label')
plt.bar(x,y)
plt.show()
=========OUTPUT========
Program 9: Drawing Histogram chart and Pie chart using Matplotlib
import matplotlib.pyplot as plt import numpy as np
# Generate some random data
data = np.random.randint(0, 100, 100) # Fixed assignment issue
# Create histogram plt.subplot(121)
plt.hist(data, bins=20)
plt.title("Histogram of random data") plt.xlabel("value")
plt.ylabel("frequency")
# Sample data
sizes = [30, 25, 20, 15, 10] labels = ['A', 'B', 'C', 'D', 'E']
# Create pie chart plt.subplot(122)
plt.pie(sizes, labels=labels) # Fixed labels issue plt.title("PIE CHART")
plt.show()
=========OUTPUT========
Program 10: Perform arithmetic operation on the Numpy arrays
import numpy as np # Initializing our array
array1 = np.arange(9, dtype=np.float64).reshape(3, 3) # array1 = np.arange(9, dtype = np.float64)
print("First Array:") print(array1)
print("Second Array:")
array2 = np.arange(11, 20, dtype=np.float64).reshape(3, 3) # Changed np.float to np.float64 # array2 = np.arange(11,20, dtype = np.int32) # Changed np.int to np.int32
print(array2)
print("\nAdding two arrays:")
print(np.add(array1, array2)) # Fixed variable name print("\nSubtracting two arrays:")
print(np.subtract(array1, array2))
print("\nMultiplying two arrays:") print(np.multiply(array1, array2))
print("\nDividing two arrays:") print(np.divide(array1, array2))
=========OUTPUT========
First Array:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
Second Array:
[[11. 12. 13.]
[14. 15. 16.]
[17. 18. 19.]]
Adding two arrays:
[[11. 13. 15.]
[17. 19. 21.]
[23. 25. 27.]]
Subtracting two arrays:
[[-11. -11. -11.]
[-11. -11. -11.]
[-11. -11. -11.]]
Multiplying two arrays:
[[ 0. 12. 26.]
[ 42. 60. 80.]
[102. 126. 152.]]
Dividing two arrays:
[[0. 0.08333333 0.15384615]
[0.21428571 0.26666667 0.3125 ]
[0.35294118 0.38888889 0.42105263]]
Program 11: Create data frame from Excel sheet using Pandas and Perform operation on data frames
import pandas as pd
# Read data from an Excel sheet in an Excel file
data = pd.read_excel('file.xlsx', sheet_name='kavita') print("\n**Displaying Data from DataFrames**\n") print(data)
print("\n**OPERATIONS ON DATAFRAMES**\n")
print("\n1. View the first few rows of the DataFrame:") print(data.head())
print("\n2. Number of rows and columns in the DataFrame:", end="") print(data.shape)
print("\n3. Filtered data (Age column < 25):") filtered_data = data[data['Age'] < 25]
print(filtered_data)
print("\n4. Sort DataFrame based on 'Age' column in ascending order:") sorted_data = data.sort_values(by='Age', ascending=True) # Fixed syntax print(sorted_data)
print("\nProgram Closed...")
Comments
Post a Comment