0% found this document useful (0 votes)
25 views17 pages

Python Programs for Basic Functions

2nd puc computer science lab manual

Uploaded by

samarth.sk.418
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)
25 views17 pages

Python Programs for Basic Functions

2nd puc computer science lab manual

Uploaded by

samarth.sk.418
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

A1.

Write a python program using a function to print Fibonacci series up


to n numbers.

def fibo(n):
f1=0
f2=1
f3=f1+f2
count=2
print(f1, f2,end=" ")
while count<n:
print(f3,end=" ")
count+=1
f1, f2=f2,f3
f3=f1 + f2
n=int(input("enter the Limit="))
fibo(n)
print()

OUTPUT :
enter the Limit=10
0 1 1 2 3 5 8 13 21 34

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 1
[Link] a Menu driven program in python to find factorial and sum of
natural umbers using a function

def fact(n):
if(n==1 or n==0):
return 1
else:
return n * fact(n -1)
def sum(n):
if(n==0):
return 0
else:
return n+sum(n-1)
num=int(input("Enter any number:"))
print("1-To find the factorial\n 2-To find the sum\n 3-Exit")
opt=int(input("Enter the option 1-3:"))
if(opt==1):
print("Factorial of",num,"is :",fact(num))
elif(opt==2):
print("Sum of",num,"is:",sum(num))
else:
print("invalid option")

OUTPUT 1:

Enter any number:10


1-To find the factorial
2-To find the sum
3-Exit
Enter the option 1-3:1
Factorial of 10 is : 3628800

OUTPUT 2:

Enter any number:10


1-To find the factorial
2-To find the sum
3-Exit
Enter the option 1-3:2
Sumof 10 is: 55

OUTPUT 3:
Enter any number:10
1-To find the factorial
2-To find the sum
3-Exit
Enter the option 1-3:5
invalid option

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 2
[Link] a python program using user defined function to calculate
interest amount using simple interest method and compound interest method
and find the difference of interest amount between the two methods.

def simp(principle,time,rate):
si=float(principle*time*rate/100)
return si
def comp(principle,time,rate):
ci= float(principle * ((1+rate/100)**time - 1))
return ci
principle = float(input('Enter amount:'))
time = float(input('Enter time:'))
rate= float(input('Enter rate:'))
si=simp(principle,time,rate)
ci=comp(principle,time,rate)
print('Simple interest is Rs.',si)
print('Compound interest is Rs.',ci)
diffint=ci-si;
print("Difference is Rs.",diffint)

OUTPUT 1:

Enter amount:5000
Enter time:12
Enter rate:8.5
Simple interest is Rs. 5100.0
Compound interest is Rs. 8308.43
Difference is Rs. 3208.43

OUTPUT 2:

Enter amount:1000
Enter time:6
Enter rate:3.3
Simple interest is Rs. 198.0
Compound interest is Rs. 215.07
Difference is Rs. 17.07

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 3
A4).Write a python program to read a text file and display the number of
vowels,consonants,uppercase and lowercase characters in the file

def count_characters(file_name):
vowels="aeiouAEIOU"
vowel_count=0
consonant_count=0
uppercase_count=0
lowercase_count=0
with open(file_name,"r") as file:
text =[Link]()
for char in text:
if [Link]():
if char in vowels:
vowel_count+=1
else:
consonant_count+=1
if [Link]():
uppercase_count+=1
elif [Link]():
lowercase_count+=1
print("Vowels:",vowel_count)
print("Consonants:",consonant_count)
print("Upper case characters:",uppercase_count)
print("Lower case characters:",lowercase_count)
def create_text_file(file_name,content):
with open(file_name,"w") as file:
[Link](content)
file_name="[Link]"
content= input("Enter few sentences to create a text file with content:")
create_text_file(file_name,content)
count_characters(file_name)
OUTPUT 1:
Enter few sentences to create a text file with content:We Love Haliyal
Vowels: 6
Consonants: 2
Upper case characters: 3
Lower case characters: 10

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 4
A5) Write a python code to count the number of lines, number of words and
number of characters in a text file.

def count_text_file(file_name):
line_count=0
word_count=0
char_count=0
with open(file_name,"r") as file:
for line in file:
line_count+=1
word_count+=len([Link]())
char_count +=len(line)
print("Lines:", line_count)
print("Words:",word_count)
print("Characters:",char_count)
def create_text_file(file_name,content):
with open(file_name,"w") as file:
[Link](content)
file_name="[Link]"
content="""Hello Students
This is a sample text file.
It contains multiple lines."""
create_text_file(file_name,content)
count_text_file(file_name)

OUTPUT 1:
Lines: 3
Words: 12
Characters: 70

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 5
A6) Write a python program to create and to read records in binary file with
student name and marks of six subjects.

import pickle
while True:
print('''[Link] Binary File.
[Link] the File.
[Link]''')
a=int(input('choose a command (1-2-3-exit):'))
if a==1:
f=open('[Link]','wb')
x=int(input('How many student:'))
for i in range(x):
name=input('Name:')
english=int(input('English Mark:'))
lan=int(input("Language Marks:"))
Eco=int(input('Economics Mark:'))
Bs=int(input('BS Mark:'))
Acc=int(input('ACC Mark:'))
cs=int(input('CS Mark:'))
t=[name,english,lan,Eco,Bs,Acc,cs]
[Link](t,f)
[Link]()
elif a==2:
f=open('[Link]','rb')
try:
while True:
p=[Link](f)
print(p)
except:
[Link]()
if a>3:
break

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 6
OUTPUT 1 :

[Link] Binary File.


[Link] the File.
[Link]
choose a command (1-2-3-exit):1
How many student:1
Name:Shivanya
English Mark:78
Language Marks:88
Economics Mark:89
BS Mark:75
ACC Mark:90
CS Mark:93
[Link] Binary File.
[Link] the File.
[Link]
choose a command (1-2-3-exit):2
['Shivanya', 78, 88, 89, 75, 90, 93]
[Link] Binary File.
[Link] the File.
[Link]
choose a command (1-2-3-exit):3
[Link] Binary File.
[Link] the File.
[Link]

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 7
[Link] a python program to copy the records of the students having
percentage 90 and above from the binary file into another file.

import pickle
while True:
print('''[Link] BinaryFile.
[Link] the main File.
[Link] new file wirh>90
[Link]''')
a=int(input('choose a command (1-2,9-exit):'))
if a==1:
f=open('[Link]','wb')
o=open('[Link]','wb')
x=int(input('How many student:'))
for i in range(x):
name=input('Name:')
english=int(input('English Mark:'))
lan=int(input("Language Marks"))
Eco=int(input('Economics Mark:'))
Bs=int(input('BS Mark:'))
Acc=int(input('Accounts Mark:'))
cs=int(input('CS Mark:'))
total=english+lan+Eco+Bs+Acc+cs
per=(total / 600)*100
t=[name,english,lan,Eco,Bs,Acc,cs,total,per]
g=[name,english,lan,Eco,Bs,Acc,cs,total,per]
[Link](t,f)
if per>=90:
[Link](g,o)
[Link]()
[Link]()
elif a==2:
f=open('[Link]','rb')
try:
while True:
p=[Link](f)
print(p)
except:

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 8
[Link]()
elif a==3:
print("Studets with> 90Marks")
f=open('[Link]','rb')
try:
while True:
o=[Link](f)
print(o)
except:
[Link]()
else:
break

OUTPUT 1:

[Link] Binary File.


[Link] the main File.
[Link] new file with Perc>90
[Link]
choose a command (1-2,9-exit):1
How many student:3
Name:A
English Mark:90
Language Marks:96
Economics Mark:98
BS Mark:99
Accounts Mark:100
CS Mark:98
Name:B
English Mark:76
Language Marks:78
Economics Mark:81
BS Mark:84
Accounts Mark:82
CS Mark:89
Name:C
English Mark:45
Language Marks:56
Economics Mark:67
BS Mark:56

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 9
Accounts Mark:59
CS Mark:61

[Link] Binary File.


[Link] the main File.
[Link] new file with Perc>90
[Link]
choose a command (1-2,9-exit):2
['A', 90, 96, 98, 99, 100, 98, 581, 96.83333333333334]
['B', 76, 78, 81, 84, 82, 89, 490, 81.66666666666667]
['C', 45, 56, 67, 56, 59, 61, 344, 57.333333333333336]
[Link] Binary File.
[Link] the main File.
[Link] new file with Perc>90
[Link]
choose a command (1-2,9-exit):3
Students with > 90 Marks
['A', 90, 96, 98, 99, 100, 98, 581, 96.83333333333334]
[Link] Binary File.
[Link] the main File.
[Link] new file with Perc>90
[Link]
choose a command (1-2,9-exit):4

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 10
[Link] a python program using function to sort the elements of a list
using bubble sort method.

def bubble_sort(arr):
n=len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]

def input_list():
arr=[]
n=int(input("Enter the number of elements in the list:"))
for i in range(n):
element =int(input("Enter element:"))
[Link](element)
return arr

arr=input_list()
print("Original list:",arr)

bubble_sort(arr)
print("Sorted list:",arr)

OUTPUT:

Enter the number of elements in the list:5


Enter element:34
Enter element:56
Enter element:23
Enter element:12
Enter element:34

Original list: [34, 56, 23, 12, 34]


Sorted list: [12, 23, 34, 34, 56]

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 11
[Link] a python program using function to sort the elements of a list
using selection sort method.

def selection_sort(arr):
n =len(arr)
for i in range(n):
min_index=i
for j in range(i+1,n):
if arr[j]<arr[min_index]:
min_index = j
arr[i],arr[min_index]=arr[min_index],arr[i]

def input_list():
arr=[]
n=int(input("Enter the number of elements in the list:"))
for i in range(n):
element= int(input("Enter element:"))
[Link](element)
return arr

arr=input_list()

print("Original list:",arr)

selection_sort(arr)
print("Sorted list:", arr)

OUTPUT:

Enter the number of elements in the list:5


Enter element:32
Enter element:45
Enter element:67
Enter element:34
Enter element:23
Original list: [32, 45, 67, 34, 23]
Sorted list: [23, 32, 34, 45, 67]

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 12
[Link] a python program using function to sort the elements of a
list using insertion sort method.

def insertion_sort(arr):
for i in range(1,len(arr)):
key =arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key

def input_list():
arr=[]
n=int(input("Enter the number of elements in the list:"))
for i in range(n):
element= int(input("Enter element:"))
[Link](element)
return arr

arr=input_list()
print("Original list:",arr)
insertion_sort(arr)
print("Sorted list using insertion sort method:",arr)

OUTPUT :

Enter the number of elements in the list:5


Enter element:55
Enter element:43
Enter element:23
Enter element:43
Enter element:65

Original list: [55, 43, 23, 43, 65]


Sorted list using insertion sort method: [23, 43, 43, 55, 65]

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 13
[Link] a python program using function to search an element in a
list using linear search method.

def linear_search(a,ele):
for i in range(len(a)):
if a[i]==ele:
return i
return -1

def input_list():
a=[]
n=int(input("Enter the number of elements in the list:"))
for i in range(n):
element=int(input("Enter element:"))
[Link](element)
return a

a=input_list()
ele=int(input("Enter the element to search for:"))

result=linear_search(a, ele)
if result!=-1:
print(ele,"Element found at Position",result)
else:
print(ele,"Element not found in the list")

OUTPUT 1 :

Enter the number of elements in the list:5


Enter element:10
Enter element:20
Enter element:30
Enter element:40
Enter element:50
Enter the element to search for:40
40 Element found at Position 3

OUTPUT 2 :

Enter the number of elements in the list:5


Enter element:10
Enter element:20
Enter element:30
Enter element:40
Enter element:50
Enter the element to search for:35
35 Element not found in the list

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 14
[Link] a python program using function to search an element in a list
using binary search method.

def binary_search(a,ele):
low=0
high=len(arr) - 1
while low<=high:
mid=(low+high)//2
if a[mid]==ele:
return mid
elif a[mid]< ele:
low=mid+1
else:
high= mid-1
return -1

def input_list():
arr=[]
n=int(input("Enter the number of elements in the list:"))
for i in range(n):
element =int(input("Enter the elements in ascending order:"))
[Link](element)
return arr

arr=input_list()
target=int(input("Enter the element to search for:"))

result=binary_search(arr, target)
if result !=-1:
print(target,"Element found at Position",result)
else:
print(target,"Element not found in the list.")

OUTPUT 1 :

Enter the number of elements in the list:5


Enter the elements in ascending order:1
Enter the elements in ascending order:2
Enter the elements in ascending order:3
Enter the elements in ascending order:4
Enter the elements in ascending order:5
Enter the element to search for:5
5 Element found at Position 4

OUTPUT 2:

Enter the number of elements in the list:3


Enter the elements in ascending order:1
Enter the elements in ascending order:2
Enter the elements in ascending order:3
Enter the element to search for:4
4 Element not found in the list.

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 15
[Link] a python program to add and display elements from a stack using
list.

stack= []
print("initially stack is empty :",stack)
[Link]('x')
[Link]('y')
[Link]('z')
print("After Pushing stack is:")
print(stack)

print('After Popped from stack:')


print([Link]())
print([Link]())
print([Link]())
print('\n my_stack after elements are popped:')
print(stack)

OUTPUT :

initially stack is empty : []


After Pushing stack is:
['x', 'y', 'z']
After Popped from stack:
z
y
x

my_stack after elements are popped:


[]

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 16
[Link] a python program to add and display elements from a queue using
list.

import queue

def display_queue(q):
print("Queue elements are:",end=" ")

while not [Link]():


element=[Link]()
print(element,end=" ")
print('\nQueue size after REMOVE is',[Link]())

q=[Link]()

[Link](10)
[Link](20)
[Link](30)
print('Queue size after INSERTION is',[Link]())

display_queue(q)

OUTPUT :

Queue size after INSERTION is 3

Queue elements are: 10 20 30

Queue size after REMOVE is 0

Department of Computer Science


V D Hegade PU College Haliyal – QQ0101 Page 17

Common questions

Powered by AI

The program calculates simple interest using the formula SI = (principle * time * rate) / 100 and compound interest using CI = principle * ((1 + rate / 100) ^ time - 1). It calculates both interest amounts based on user inputs and then determines the difference by subtracting simple interest from compound interest, showcasing the impact of compounding over time .

Binary search requires a sorted list to function correctly, as it divides the list into halves to locate the target element. This method reduces the search space logarithmically, offering a time complexity of O(log n). It is advantageous for large datasets compared to linear search due to its efficiency, but it mandates pre-sorting the list, which could be a drawback if the list is frequently updated .

Insertion sort operates by selecting one element at a time from the unsorted portion and inserting it into the appropriate position within the sorted portion of the list. It does this by iterating from the second element to the last, shifting larger elements in the sorted section one position to the right to make space, which has a typical time complexity of O(n^2) but is efficient for small or partially sorted arrays .

The bubble sort function iteratively passes through the list, compares adjacent elements, and swaps them if they are out of order. This process repeats for each element until the list is sorted, with each full iteration moving the largest unsorted element to its correct position. The process has a time complexity of O(n^2) and sorts the list in-place .

The linear search function iterates through each element of the list sequentially, comparing it with the target element. While simple and easy to understand, its effectiveness decreases with large lists due to its O(n) time complexity, leading to slower execution compared to more advanced algorithms like binary search, which is preferable for large, sorted lists .

The program differentiates between factorial calculation and sum of natural numbers through a menu-driven interface. The user selects an option to either calculate the factorial or the sum, based on which the program calls the appropriate function: `fact(n)` for factorial and `sum(n)` for the sum. If an invalid option is chosen, it prompts an error message .

The character counting program reads a text file, iterating through each character. It checks if a character is an alphabetic one, then distinguishes whether it is a vowel or consonant using a list of vowels. It also keeps track of whether the character is uppercase or lowercase by using `isupper()` and `islower()` methods, respectively .

The error checking in the binary student data file program is minimal, relying primarily on try-except blocks to catch EOF exceptions while reading records. This approach prevents the program from crashing when it reaches the end of the file, but it lacks input validation and error messages, which limits its robustness in handling various user input errors or file corruption issues .

Selection sort works by repeatedly identifying the smallest (or largest) unsorted element and moving it to the end of the sorted portion of the list. It maintains two sublists: a sorted sublist and an unsorted sublist. In each iteration, the minimum element from the unsorted sublist is swapped with the left-most unsorted element, expanding the sorted sublist by one .

The Fibonacci series program uses a while loop that executes as long as the count is less than 'n'. It initializes f1=0 and f2=1, then iteratively calculates the next number (f3 = f1 + f2), printing each number until the count reaches n .

You might also like