0% found this document useful (0 votes)
6 views9 pages

Pycode

A compilation of python programs for learning python like never before and unlock your future potential as a coder.
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)
6 views9 pages

Pycode

A compilation of python programs for learning python like never before and unlock your future potential as a coder.
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

Python Programs

#1. Program to slice a list containing number into two slices and find
the sum of the first one and the average of the next one.

lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

slc1 = lst[0:10]

slc2 = lst[10:-1]

sum = avg = 0

print("slice 1")

for a in slc1:

sum += a

print(a, end=" ")

print()

print("Sum of all element in slice 1 is :", sum)

print("slice 2")

for b in slc1:

sum += b

print(b, end=" ")

print()

avg = sum / len(slc2)

print("Average of all the elements in slice 2 is :", avg)

#2 Program to create a 2D list in python.


lst = [ ]
r = int(input("How many rows? :"))
c = int(input("How many columns? :"))

for i in range(r):
row = [ ]

for j in range(c):
elem = int(input("Element" + str(i) + "," + str(j) + ":"))
row.append(elem)
lst.append(row)

print("List created is :", lst)


#3 Program to read email ids of n number of students and store them in a
tuple. Create 2 new tuples,one to store only the usernames from the email id
and the second to store domain names from the email ids. Print all 3 tuples at
the end of the program.
lst = [ ]
n = int(input("How many students?! --> "))
for i in range(1, n+1):
email = input("Enter email id of the student" + str(i) + " : ")
lst.append(email) # EMAIL TUPLE CREATED

etuple = tuple(lst)

lst1 = [ ]
lst2 = [ ]

for i in range(n):
email = etuple[i].split("@")
lst1.append(email[0]) # USERNAME TUPLE CREATED
lst2.append(email[1]) # DOMAIN TUPLE CREATED

Uname_Tup = tuple(lst1)
dom = tuple(lst2)

print("Student Email IDs :--")


print(etuple)

print("User name tuple :--")


print(Uname_Tup)

print("Domain Tuple :--")


print(dom)
#4 Program to read the roll nos and marks of n number of students with the roll nos as
keys and the marks as values and also ask whether the input needs any modifica on or
not.
M = { }
n = int(input("How many students bro? --> "))
for x in range(n):
r, m = eval(input("Enter Roll number, Marks = "))
M[r] = m
print("Created dictionary -->")
print(M)
print("Do you want to modify any marks? --> YES | NO")
x = input("Enter --> ")

if x == "YES":
r = int(input("Enter roll number: "))
if r in M:
M[r] = float(input("Enter new marks: "))
else:
print("No such roll number found")
print("modified dictionary -->")
print(M)

if x == "NO":
print("Thank YOU")

#5 Program to count the frequencies of a list of elements using a


dic onary.
import json
sentence = "This is a great idea to be very very honest. oh my god I talk too
much. But jokes apart, this can change it all"

words = sentence.split()
d = {}
for x in words:
key = x
if key not in d:
count = words.count(key)
d[key] = count

print("Counting frequencies in the list :-", words)


print(json.dumps(d, indent=1))

#6 Program to find the maximum,minimum,sum of keys of


numbers as given below.
numbers = {1:111, 2:222, 3:333, 4:444}
print("Given dictionary -->", numbers)

max_key = max(numbers)
min_key = min(numbers)
print("Maximum key :", max_key, "minimum key :", min_key)

max_value = max(numbers.values())
min_value = min(numbers.values())
print("Maximum value :", max_value, "minimum value :", min_value)

sum_keys = sum(numbers)
sum_values = sum(numbers.values())
print("sum of values of dictionary", sum_values)
print("sum of keys of dictionary", sum_keys)

#7 Program to read the roll number and marks of 5 students with


the roll number as key and the marks as the values.
rno = []
mrks = []
for a in range(5):
r, m = eval(input("Enter roll number, marks:"))
rno.append(r)
mrks.append(m)

d = {rno[0]: mrks[0], rno[1]: mrks[1], rno[2]: mrks[2],


rno[3]: mrks[3], rno[4]: mrks[4]}

print("Created Dictionary is -->")


print(d)

#8 Program to print two statement in a single line using while loop.


i = 1
while i <= 10:
print("Spandan", end = " ")
i = i + 1

j = 1
while j <= 7:
print("Kaka", end = " ")
j = j + 1
i=i+1
print()

#9 Program to find the sum of all odd number between a


range.
i = 1
sum1 = 0
t = int(input("Enter the maximum range"))

while i <= t:
sum1 = sum1 + i
i = i + 2
print("The value of i ->> {}",format(i))
print("The sum of all odd number in the given range is {}",format(sum1))
#10 Program to calculate the sum, difference, product,division and
modulo between 2 number through a function.
def operation(x, y):
s = x + y
d = x - y
p = x * y
di = x / y
mod = x % y
return s, d, p, di, mod

num1 = int(input("Enter the first number:-"))


num2 = int(input("Enter the second number:-"))
print("The sum, difference, product, division and modulo of the numbers", num1,
"and", num2, "are respectively as follows")

a = operation(num1, num2)
print(a)

#11 Program to create a function in python to calculate the


volume of a box with default parameters always provided.
def volume(l = 2, b = 5, h = 10):
return (l * b * h)

print("Volume with default values is as follows:")


vol1 = volume()
print(vol1)

len = int(input("Enter the length:-->"))


bre = int(input("Enter the breadth:-->"))
hei = int(input("Enter the height:-->"))

print("The volume with provided values becomes:")


vol2 = volume(len, bre, hei)
print(vol2)
#12 Program to calculate the average of 3 numbers using a
function.
def calcsum(a, b, c):
s = a + b + c
return s

def average(x, y, z):


sm = calcsum(x, y, z)
return sm / 3

num1 = int(input("Enter the first number:-"))


num2 = int(input("Enter the second number:-"))
num3 = int(input("Enter the third number:-"))

l = average(num1, num2, num3)


print("The average of 3 numbers is :-", l)

#13 Write a program to get roll numbers,names and marks


of the student of a class and store these values in a file called
“marks.txt”
Count = int(input("Enter the total no. of students in the class:"))
fileout = open("marks.txt", "w")

for i in range(Count):
print("Enter details of the student", (i+1), "below")
roll = int(input("Enter roll number:"))
name = input("Name:")
marks = float(input("Marks:"))
rec = str(roll) + "," + name + "," + str(marks) + '\n'
fileout.write(rec)

fileout.close()
#14 WAP to open file student.dat and search for
records with certain roll numbers.
import pickle
search_keys = [1, 9]

try:
with open("content/student.dat", "rb") as file:
print("Searching in student.dat...")
found = False

while True:
try:
stu = pickle.load(file)
if stu["Roll"] in search_keys:
print(stu)
found = True
except EOFError:
break

if not found:
print("No such records found")
else:
print("Search successful")

except FileNotFoundError:
print("File not Found")

#15 WAP to create a CSV file to store student


data(Roll no,Name,Marks). Obtain data from the user
and write 5 records into the file.
import csv
x = open("Student.csv", "w")
stuwriter = csv.writer(x)
stuwriter.writerow(["Roll Number", "Name", "Marks"])
for i in range(2):
print("Student", (i + 1))
roll_no = int(input("Enter the roll number: "))
name = input("Enter name of the student: ")
marks = float(input("Enter the marks obtained: "))
stu_rec = [roll_no, name, marks]
stuwriter.writerow(stu_rec)

x.close()

JK

You might also like