0% found this document useful (0 votes)
23 views37 pages

Tanisha XII

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views37 pages

Tanisha XII

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

ST.

MARY’S CONVENT SCHOOL


GAJRAULA

SESSION 2024 – 2025

SUBMITTED TO :- SUBMITTED BY:-


TANISHA
SINGH
XIIth
PYTHON FUNCTIONS
Q1 Add two numbers

Def add(a, b):


return a + b

Q2 Multiply two. Numbers


Def multiply(a, b):
return a * b

Q3Find Maximum of two numbers


Def find_max(a, b, c):
return max(a, b, c)

Q4 Check odd or even


def odd_or_even(n):
return “Even” if n % 2 == 0:
else “Odd”

Q5 FIND FACTORIAL

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n – 1)
Q6 Fibonacci sequence
def fibonacci(n):
sequence = []
a, b = 0, 1
while len(sequence) < n:
sequence.append(a)
a, b = b, a + b
return sequence

Q7. Reverse a string


def reverse_string(s):
return s[::-1]
Q8 check prime number
def is_prime(n):
if n < 2:
return False
for I in range(2, int(n ** 0.5) + 1):
if n % I == 0:
return False
return True
Q 9 sum of list elements
def sum_of_list(lst):
return sum(lst)
Q10 Palindrome check
def is_palindrome(s):
return s == s[::-1]

Q11Count vowels
def count_vowels(s):
return sum(1 for char in s.lower() if char in “aeiou”)

Q12 Convert celsius into fahrenheit


def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
Q13 Find GCD
def find_gcd(a, b):
while b:
a, b = b, a % b
return a

Q14 Find power of a number


def power(base, exp):
return base ** exp

Q15 check leap year.


def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 ==
0)
Q16Find length of a string
def string_length(s):
return len(s)

Q17Sort a list
def sort_list(lst):
return sorted(lst)

Q18 Find area of a circle


import math
def area_of_circle(radius):
return math.pi * radius ** 2
Q19 Counts words in a string
def count_words(s):
return len(s.split())

Q20 Check Armstrong number


def is_armstrong(n):
digits = list(map(int, str(n)))
return n == sum(d ** len(digits) for d in digits)
CALLING STATEMENT AND THEIR
OUTPUT
1)result= add(4, 5)
. print(result)
Output
9

2)Result=multiply(3,7)
Print ( result)
Output
21

3)print(find_max(10,20,15))
Output
20
4)print(odd_or_even(8))
Output
Even

5)Print(factorial (5))
Output
120

6)Print( Fibonacci (5))


Output
[0,1,1,2,3]
7)Print(reverse_string(“PYTHON”))
Output
Nohtyp

8)Print(is_prime(17))
Output
True

9)Print (sum_of_list([1,2,3,4]))
Output
10
10) print(is_palindrome(“madam”))
Output
True

11)Print(count vowels (“hello world”))


Output
3

12)Print(celsius _to_fahrenheit(0))
Output
32.0
13) print(find_gcd(48,18))
Output
6

14)Print(power(2,3))
Output
8

15) print(is_leap_year(2024))
Output
True
16)print(string_length(“python”))
Output
6

17)Print(sort_list([4,2,9,1]))
Output
[1,2,4,9]

18) Print (area_of_circle(7))


Output
153.93804002589985
19)Print (count_ words(“python is a fun language”))
Output
5

20)Print(is_armstrong(153))
Output
True
CSV
FILE
21 Program to store student details
Import csv

# Function to add student details


def add_student_details(filename):
num_students = int(input(“Enter the number of students: “))
with open(filename, ‘w’, newline=‘’) as file:
writer = csv.writer(file)
writer.writerow([‘Roll Number’, ‘Name’, ‘Class’, ‘Marks’])
for _ in range(num_students):
roll_number = input(“Enter Roll Number: “)
name = input(“Enter Name: “)
class_name = input(“Enter Class: “)
marks = input(“Enter Marks: “)
def display_student_details(filename):
print(“\nStored Student Details:”)
with open(filename, ‘r’) as file:
reader = csv.reader(file)
for row in reader:
print(row)
filename = ‘students.csv’
add_student_details(filename)
display_student_details(filename)

Enter the number of students: 2


Enter Roll Number: 101
Enter Name: Alice
Enter Class: 12
Enter Marks: 85
Enter Roll Number: 102
Enter Name: Bob
Enter Class: 12
Student details saved successfully.

Stored Student Details:


[‘Roll Number’, ‘Name’, ‘Class’, ‘Marks’]
[‘101’, ‘Alice’, ‘12’, ‘85’]
[‘102’, ‘Bob’, ‘12’, ‘90’]

22).Appending data to a CSV file


Import csv

# Appending data to a CSV file


new_data = [‘Diana’, 28, ‘Houston’]

with open(‘output.csv’, ‘a’, newline=‘’) as file:


writer = csv.writer(file)
writer.writerow(new_data)

print(“New data appended to output.csv”)


Output
Name,Age, city
Alice,25,New York
Bob,30,Los Angeles
Charlie,22,Chicago
Diana,28,Houston

23) Writing to a Csv file


Import csv

# Writing to a CSV file


data = [
[‘Name’, ‘Age’, ‘City’],
[‘Alice’, 25, ‘New York’],
[‘Bob’, 30, ‘Los Angeles’],
[‘Charlie’, 22, ‘Chicago’]
]

with open(‘output.csv’, ‘w’, newline=‘’) as file:


writer = csv.writer(file)
writer.writerows(data)
Output
Name,Age,City
Alice,25,New York
Bob,30,Los Angeles
Charlie,22,Chicago
TEXT FILE PROGRAMMES

24)WRITE TO A FILE
# Write to a text file
with open(“example.txt”, “w”) as file:
file.write(“Hello, this is the first line.\n”)
file.write(“This is the second line.”)
print(“Data written to example.txt”)
Output
Data written to example.txt

25)READ FROM A FILE


# Read a text file
with open(“example.txt”, “r”) as file:
content = file.read()
print(“File content:”)
print(content)
Output
File content:
Hello, this is the first line.
This is the second line.
26)APPEND TO A FILE
# Append to a text file
# Append to a text file
with open(“example.txt”, “a”) as file:
file.write(“\nThis is an appended line.”)
print(“Data appended to example.txt”)
Output
Data appended to example.txt
#BINARY FILES
27)To create item details
import pickle
def create():
d={}
xf=open(“item.dat”,”wb”)
wish=‘y’
while wish==‘y’:
itno=int(input(“Enter a no”))
desc=input(“Enter description”)
qty=int(input(“Enter quantity”))
rate=int(input(“Enter rate”))
d[“itno”]=itno
d[“desc”]=desc
d[“qty”]=qty
d[“rate”]=rate
pickle.dump(d,xf)
wish=input(“Add(y/n)”)
xf.close()
create()
28)To display the contents of the file
import pickle
def display():
d={}
xf=open(“item.dat”,”rb”)
try:
while True:
d=pickle.load(xf)
print(d)
except EOFError:
xf.close()
display()
29)To select an item no.
import pickle
def search():
k=0
d={}
xf=open(“item.dat”,”rb”)
n=int(input(“Enter no to be searched”))
try:
while True:
d=pickle.load(xf)
if d[“itno”]==n:
k=1
print(d)
except EOFError:
if k==0:
print(“Not Found”)
xf.close()
search()

30)To the read the file of specific item no.


import pickle
def modify():
xf=open(“item.dat”,”rb+”)
d={}
n=int(input(“Enter no to be search and modify”))
try:
while True:
rec=xf.tell()
d=pickle.load(xf)
if d[“itno”]==n:
d[“rate”]=d[“rate”]+d[“rate”]*3/100
xf.seek(rec)
pickle.dump(d,xf)
except EOFError:
xf.close()
modify()
31) To delete the record
import os
def delfile():
k=0
xf=open(“item.dat”,”rb”)
yf=open(“temp.dat”,”wb”)
n=int(input(“Enter item no to be deleted”))
d={}
try:
while True:
d=pickle.load(xf)
if d[“itno”]!=n:
pickle.dump(d,yf)
except EOFError:
xf.close()
yf.close()
os.remove(“item.dat”)
os.rename(“temp.dat”,”item.dat”)
delfile()
#BUBBLE SORT:-
‘’’32.WAF bsort()to arrange a list in ascending order using bubble sort’’’
def bsort(l):
for I in range(len(l)):
for j in range(0,len(l)-i-1):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
print(l)
l=eval(input(“enter a list :”))
bsort(l)
#OUTPUT
enter a list :[3,5,2,1,5,6,8,3,0,4,2,0,7,8,9]
[0, 0, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9]

#INSERTION SORT:-
‘’’33.WAF isort()to arrange a list in ascending order using insertion sort.’’’
def isort(l):
for I in range (1,len(l)):
t=l[i]
j=i-1
while t<l[j] and j>=0:
l[j+1]=l[j]
j=j-1
l[j+1]=t
print(l)
L=eval(input(“enter a list :”))
isort(l)
#OUTPUT
enter a list :[3,5,2,1,5,6,8,3,0,4,2,0,7,8,9]
[0, 0, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9]

#SEARCHING

#LINEAR SEARCH:-
‘’’34.WAF TO PASS A LIST AND A NO. AND SEARCH IT IF FOUND RETURN 1 OTHERWISE -1’’’
def linear_search(l,n):
k=-1
for I in l:
if i==n:
k=1
print(k)
l=eval(input(“enter a list :”))
n=int(input(“enter no. :”))
linear_search(l,n)
#OUTPUT
enter a list :[1,4,6,7]
enter no. :6
1
#BINARY SEARCH:-
‘’’35.WAF to pass a list and a no. and search it using binary search.’’’
def binary_search(l,n):
k=0
beg=0
last=len(l)-1
while beg<=last:
mid=int((beg+last)/2)
if l[mid]==n:
k=1
break
elif l[mid]>n:
last=mid-1
elif l[mid]<n:
beg=mid+1
if k==0:
print(“not found”)
else:
print(“it is found”)
l=eval(input(“enter a list”))
n=int(input(“enter a no.”))
binary_search(l,n)
#OUTPUT
enter a list[1,2,3]
enter a no.1
it is found
#2D LIST (MATRIX)
‘’’36WAF that passes a 2d list and find the sum of first and last column’’’
def twod(l,r,c):
for I in range®:
print(l[i][0]+l[i][c-1])
l=[]
r=int(input(“enter no. of rows”))
c=int(input(“enter no. of columns”))
for I in range®:
row=[]
for j in range©:
x=int(input(“enter no.”))
row.append(x)
l.append(row)
twod(l,r,c)
#OUTPUT
enter no. of rows2
enter no. of columns2
enter no.1
enter no.2
enter no.3
enter no.4
3
7
# Stack Implementation
‘’’
Stack: implemented as a list
Top: Integer having position of topmost element in stack
‘’’
def isempty(stk):
if stk == []:
return True
else:
return False

def push(stk, item):


stk.append(item)

def pop(stk):
if isempty(stk):
return “underflow”
else:
item = stk.pop()
return item

def peek(stk):
if isempty(stk):
return “underflow”
else:
return stk[-1]
Def display(stk):
if isempty(stk):
print(“stack empty”)
else:
print(stk[-1], “<-top”)
for a in range(len(stk)-2, -1, -1):
print(stk[a])

# MAIN
stack = []
while True:
print(“Stack operation”)
print(“1. Push”)
print(“2. Pop”)
print(“3. Peek”)
print(“4. Display stack”)
print(“5. Exit”)
ch = int(input(“Enter your choice (1-5): “))

if ch == 1:
item = int(input(“Enter item: “))
push(stack, item)
elif ch == 2:
item = pop(stack)
if item == “underflow”:
print(“Underflow! Stack is empty!”)
else:
print(“Popped item is”, item)
elif ch == 3:
item = peek(stack)
if item == “underflow”:
print(“Underflow! Stack is empty”)
else:
print(“Topmost item is”, item)
elif ch == 4:
display(stack)
elif ch == 5:
break
else:
print(“Invalid choice”)
#OUTPUT
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):1
Enter item :1
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):1
Enter item :2
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):1
Enter item :4
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):1
Enter item :5
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):4
5 <-top
4
2
1
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):3
Topmost item is 5
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):2
Popped item is 5
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):5

You might also like