0% found this document useful (0 votes)
5 views2 pages

Python Programs

The document contains multiple Python programs that demonstrate various functionalities such as student details and marks calculation, age determination based on year of birth, Fibonacci sequence generation, binomial coefficient calculation, statistical analysis (mean, variance, standard deviation), frequency counting of digits and words in a text file, file sorting, complex number operations, and directory backup into a zip file. Each program includes user input prompts and outputs results based on the provided data. The document serves as a collection of coding examples for educational purposes.

Uploaded by

Deepa Gowda
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)
5 views2 pages

Python Programs

The document contains multiple Python programs that demonstrate various functionalities such as student details and marks calculation, age determination based on year of birth, Fibonacci sequence generation, binomial coefficient calculation, statistical analysis (mean, variance, standard deviation), frequency counting of digits and words in a text file, file sorting, complex number operations, and directory backup into a zip file. Each program includes user input prompts and outputs results based on the provided data. The document serves as a collection of coding examples for educational purposes.

Uploaded by

Deepa Gowda
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/ 2

In [22]: # program 1A student deatails , marks and percentage

name=input("enter the student name: ")


usn=input("enter the student usn: ")
m1=int(input("enter the subject 1 marks: "))
m2=int(input("enter the subject 2 marks: "))
m3=int(input("enter the subject 3 marks: "))

total=m1+m2+m3
percentage=(total/300)*100
print("%28s"%"Student details","\n =====================================")
print("%20s"%("Name: "),name)
print("%20s"%("USN: "),usn)
print("%20s"%("Marks 1: "),m1)
print("%20s"%("Marks 2: "),m2)
print("%20s"%("Marks 3: "),m3)
print("%20s"%("total: "),total)
print("%20s"%("percentage: "),percentage,"%")
print("\n ==================================")

Student details
=====================================
Name: Ashvika Gowda
USN: 08
Marks 1: 100
Marks 2: 99
Marks 3: 98
total: 297
percentage: 99.0 %

==================================

In [12]: # program 1B year of birth and calculate age

name=input("enter the person's name: ")


yob=int(input("enter the year of birth: "))
current_year=2024
age=current_year-yob
if age>60:
print(name," you are a senior citizen.")
else:
print(name," you are not a senior citizen.")

Ashvika you are not a senior citizen.

In [26]: # program 2A fibonacci sequence

num=int(input("enter the lenght of the fibonacci sequence : "))


first_term =0
second_term=1
print("The fibonacci sequence with ",num," is: ")
print(first_term,second_term,end=" ")
for i in range(2,num):
current_term=first_term+second_term
print(current_term,end=" ")
first_term=second_term
second_term=current_term

The fibonacci sequence with 10 is:


0 1 1 2 3 5 8 13 21 34

In [44]: #program 2B BINOMIAL FACTORIAL

def fact(num):
if num==0:
return 1
else:
return num*fact(num-1)
n=int(input("enter the value of n: "))
r=int(input("enter the value of r: "))
ncr=fact(n)/(fact(r)*fact(n-r))
print(n,"C",r," = ","%d"%ncr,sep ="")

5C3 = 10

In [58]: # PROGRAM 3 MEAN , VARIANCE AND STANDARD VARIANCE

from math import sqrt


mylist=[ ]
num=int(input("enter the number of elements in elements in your list: "))
for i in range(num):
val=int(input("enter the elements: "))
mylist.append(val)
print("the lenght of the list is ",len(mylist))
print("the list contains ",mylist)
total=0
for elem in mylist:
total+=elem
mean=total/num
total=0
for elem in mylist:
total+=(elem-mean)*(elem-mean)
variance=total/num
stdev=sqrt(variance)
print("mean = ",mean)
print("variance = ",variance)
print("standard variance = ",stdev)

the lenght of the list is 5


the list contains [11, 22, 33, 44, 55]
mean = 33.0
variance = 242.0
standard variance = 15.556349186104045

In [62]: # Program 4 frequency of each digit

message=input("Enter the a multi-digit number")


count={ }
for character in message:
count.setdefault(character,0)
count[character]=count[character]+1
print(count)

{'1': 6, '2': 1, '4': 1, '5': 1, '9': 2, '6': 1}

In [80]: # program 5 frequently appering words from text file

import sys
import string
import os.path

fname=input("enter the file name : ")


if not os.path.isfile(fname):
print("file named ",fname," does'nt exist.")
sys.exit(0)

infile=open(fname,"r")

file_contents=" "

for line in infile:


for ch in line:
if ch not in string.punctuation:
file_contents=file_contents+ch
else:
file_contents=file_contents+""
word_freq={}
word_list=file_contents.split()

for word in word_list:


if word not in word_freq.keys():
word_freq[word]=1
else:
word_freq[word]+=1

sorted_word_freq=sorted(word_freq.items(),key=lambda x:x[1],reverse=True)

print("\n =================================================")
print(" 10 most frequently appering words and their count")
print("\n ==================================================")

for i in range(10):
print(sorted_word_freq[i][0]," : occurs ",sorted_word_freq[i][1],"times.")

=================================================
10 most frequently appering words and their count

==================================================
the : occurs 7 times.
of : occurs 3 times.
in : occurs 2 times.
The : occurs 1 times.
sun : occurs 1 times.
dipped : occurs 1 times.
below : occurs 1 times.
horizon : occurs 1 times.
painting : occurs 1 times.
sky : occurs 1 times.

In [24]: # program 06 to sort the contents of text file and write the sorted contents into seprate textfile

def sort_file_contents(input_file,output_file):
try:
with open (input_file,'r') as file:
lines=file.readlines()
stripped_lines=[line.strip() for line in lines]
stripped_lines.sort()

with open (output_file,'w') as file:


for line in stripped_lines:
file.write(line+'\n')
print(f" contents sorted and written to {output_file} successfully")
except FileNotFoundError:
print(f"Error: The file {input_file} does not exist")
except Exception as e:
print (f"an error occurred :{e}")

input_file='input1.txt'
output_file='sorted_output.txt'
sort_file_contents(input_file,output_file)

#text file name should as same as input_file='input1.txt' name defined here .

contents sorted and written to sorted_output.txt successfully

In [6]: # program 08 write a function named divexp which takes two parameters

import sys
def DivExp(a,b):
assert a>0,"a should be greater than o "
try:
c=a/b
except ZeroDivisionError:
print("value of b cannot be zero ")
sys.exit(0)
else:
return c

v1=int(input("enter the value of a: "))


v2=int(input("enter the value of b: "))
v3=DivExp(v1,v2)
print(v1,"/",v2,"=",v3)

9 / 9 = 1.0

In [4]: # program 09 complex number

class complex():

def __init__(self,realp=0,imagp=0):
self.realp=realp
self.imagp=imagp

def setcomplex(self,realp,imagp):
self.realp=realp
self.imagp=imagp

def readcomplex(self):
self.realp=int(input("enter the real part : "))
self.imagp=int(input("enter the imaginary part : "))

def showcomplex(self):
print('(',self.realp,')','+i','(',self.imagp,')',sep=" ")

def addcomplex(self,c2):
c3=complex()
c3.realp=self.realp+c2.realp
c3.imagp=self.imagp+c2.imagp
return c3

def add2complex(a,b):
c=a.addcomplex(b)
return c

def main( ):
c1=complex(3,5)
c2=complex(6,4)
print (" complex number 1: ")
c1.showcomplex()
print (" complex number 2: ")
c2.showcomplex()
c3=add2complex(c1,c2)
print("sum of 2 complex numbers:")
c3.showcomplex()
complist=[]
num=int(input("\n Enter the value of N: "))

for i in range(num):
print("object ",i+1)
obj=complex()
obj.readcomplex()
complist.append(obj)
print("\n Entered complex numbers are: ")
for obj in complist:
obj.showcomplex()
sumobj = complex()
for obj in complist:
sumobj=add2complex(sumobj,obj)
print("\n sum of N complex numbers is ", end=" ")
sumobj.showcomplex()
main()

complex number 1:
( 3 ) +i ( 5 )
complex number 2:
( 6 ) +i ( 4 )
sum of 2 complex numbers:
( 9 ) +i ( 9 )
object 1
Entered complex numbers are:
object 2
Entered complex numbers are:
object 3
Entered complex numbers are:
( 1 ) +i ( 1 )
( 3 ) +i ( 2 )
( 5 ) +i ( 4 )

sum of N complex numbers is ( 9 ) +i ( 7 )

In [89]: # program 10 student details using getmarks() & display()

class Student:
def __init__(self, name = "", usn = " ", score = [0,0,0,0]):
self.name = name
self.usn = usn
self.score = score
def getMarks(self):
self.name = input("Enter student Name : ")
self.usn = input("Enter student USN : ")
self.score[0] = int(input("Enter marks in Subject 1 : "))
self.score[1] = int(input("Enter marks in Subject 2 : "))
self.score[2] = int(input("Enter marks in Subject 3 : "))
self.score[3] = self.score[0] + self.score[1] + self.score[2]
def display(self):
percentage = self.score[3]/3
spcstr = "=" * 81
print(spcstr)
print("SCORE CARD DETAILS".center(81))
print(spcstr)
print("%15s"%("NAME"), "%12s"%("USN"), "%8s"%"MARKS1","%8s"%"MARKS2","%8s"%"MARKS3","%8s"%"TOTAL","%12s"%("PERCENTAGE"))
print(spcstr)
print("%15s"%self.name, "%12s"%self.usn, "%8d"%self.score[0],"%8d"%self.score[1],"%8d"%self.score[2],"%8d"%self.score[3],"%12.2f"%percentage)
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
main()

=================================================================================
SCORE CARD DETAILS
=================================================================================
NAME USN MARKS1 MARKS2 MARKS3 TOTAL PERCENTAGE
=================================================================================
Ashvika Gowda 08 100 100 100 300 100.00
=================================================================================

In [4]: class Complex ():


def initComplex (self) :
self.realPart = int (input ("Enter the Real Part: "))
self.imgPart = int (input ("Enter the Imaginary Part: "))
def display (self) :
print (self.realPart,"+", self.imgPart, "i", sep="")
def sum (self, cl, c2) :
self.realPart = cl.realPart + c2. realPart
self.imgPart = cl.imgPart + c2.imgPart
cl = Complex ()
c2 = Complex ()
c3 = Complex ()

print ("Enter first complex number")


cl.initComplex ()
print ("First Complex Number: ", end="")
cl. display()
print ("Enter second complex number")
c2. initComplex ()
print ("Second Complex Number: ", end="")
c2. display ()
print ("Sum of two complex numbers is ", end="")
c3. sum (cl, c2)
c3. display ()

Enter first complex number


First Complex Number: 6+7i
Enter second complex number
Second Complex Number: 9+8i
Sum of two complex numbers is 15+15i

In [1]: import os
import sys
from pathlib import Path
import zipfile

dirName = input('Enter the directory name that you want to back up: ')

if not os.path.isdir(dirName):
print('Directory', dirName, "doesn't exist.")
sys.exit(0)

curDirectory = Path(dirName)

with zipfile.ZipFile('myzip.zip', mode='w') as archive:


for file_path in curDirectory.rglob('*'):
archive.write(file_path, arcname=file_path.relative_to(curDirectory))

if os.path.isfile('myzip.zip'):
print('Archive', 'myzip.zip', 'created successfully.')
else:
print('Error in creating zip archive.')
Archive myzip.zip created successfully.

In [ ]:

You might also like