0% found this document useful (0 votes)
2 views10 pages

Python Lab Rcord

The document contains various Python programs demonstrating different functionalities such as checking prime numbers, a menu-driven calculator, student grades using a dictionary, file copying, matrix addition, character frequency counting, Armstrong number checking, and more. Each program includes user input prompts, logic implementation, and sample outputs. The programs serve as practical examples for beginners to understand basic programming concepts and operations.

Uploaded by

soloclimber1015
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)
2 views10 pages

Python Lab Rcord

The document contains various Python programs demonstrating different functionalities such as checking prime numbers, a menu-driven calculator, student grades using a dictionary, file copying, matrix addition, character frequency counting, Armstrong number checking, and more. Each program includes user input prompts, logic implementation, and sample outputs. The programs serve as practical examples for beginners to understand basic programming concepts and operations.

Uploaded by

soloclimber1015
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/ 10

1.

Check Prime Numbers in a Range and Count Them


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

start = int(input("Enter start of range: "))


end = int(input("Enter end of range: "))
count = 0
print(f"Prime numbers between {start} and {end}:")
for num in range(start, end + 1):
if is_prime(num):
print(num, end=' ')
count += 1
print(f"\nTotal prime numbers: {count}")

Output:

sql
CopyEdit
Enter start of range: 10
Enter end of range: 30
Prime numbers between 10 and 30:
11 13 17 19 23 29
Total prime numbers: 6

2. Menu-Driven Calculator
python
CopyEdit
def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b if b != 0 else "Undefined"
while True:
print("\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Exit")
choice = int(input("Enter choice: "))
if choice == 5:
break
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

if choice == 1:
print("Result:", add(a, b))
elif choice == 2:
print("Result:", sub(a, b))
elif choice == 3:
print("Result:", mul(a, b))
elif choice == 4:
print("Result:", div(a, b))
else:
print("Invalid choice!")

Output (Example):

mathematica
CopyEdit
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice: 1
Enter first number: 5
Enter second number: 3
Result: 8.0

3. Student Grades Using Dictionary


python
CopyEdit
n = int(input("Enter number of students: "))
students = {}
for _ in range(n):
name = input("Enter student name: ")
marks = list(map(int, input("Enter marks for 3 subjects:
").split()))
students[name] = {"marks": marks, "avg": sum(marks)/3}

print("\nStudent Report:")
for name, data in students.items():
grade = "A" if data["avg"] >= 75 else "B" if data["avg"] >= 50
else "C"
print(f"{name}: Marks={data['marks']} Avg={data['avg']:.2f}
Grade={grade}")

Output:

yaml
CopyEdit
Enter number of students: 2
Enter student name: Ravi
Enter marks for 3 subjects: 80 70 75
Enter student name: Meena
Enter marks for 3 subjects: 40 50 45

Student Report:
Ravi: Marks=[80, 70, 75] Avg=75.00 Grade=A
Meena: Marks=[40, 50, 45] Avg=45.00 Grade=C

4. Program to Perform File Copy


python
CopyEdit
source = input("Enter source filename: ")
dest = input("Enter destination filename: ")

try:
with open(source, "r") as src:
content = src.read()
with open(dest, "w") as dst:
dst.write(content)
print("File copied successfully.")
except FileNotFoundError:
print("Source file not found.")

Output:

mathematica
CopyEdit
Enter source filename: input.txt
Enter destination filename: backup.txt
File copied successfully.

5. Matrix Addition
python
CopyEdit
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))

print("Enter elements for first matrix:")


mat1 = [[int(input()) for _ in range(cols)] for _ in range(rows)]

print("Enter elements for second matrix:")


mat2 = [[int(input()) for _ in range(cols)] for _ in range(rows)]

result = [[mat1[i][j] + mat2[i][j] for j in range(cols)] for i in


range(rows)]

print("Resultant Matrix:")
for row in result:
print(row)

Output (Example):

yaml
CopyEdit
Enter number of rows: 2
Enter number of columns: 2
Enter elements for first matrix:
1
2
3
4
Enter elements for second matrix:
5
6
7
8
Resultant Matrix:
[6, 8]
[10, 12]

6. Count Character Frequency in File


python
CopyEdit
filename = input("Enter filename: ")
freq = {}
try:
with open(filename, "r") as f:
text = f.read()
for char in text:
if char.isalpha():
freq[char] = freq.get(char, 0) + 1
print("Character frequencies:")
for char, count in freq.items():
print(f"{char}: {count}")
except FileNotFoundError:
print("File not found.")

Output:

yaml
CopyEdit
Enter filename: input.txt
Character frequencies:
T: 2
e: 4
s: 2
t: 3

7. Armstrong Number Checker (3-digit)


python
CopyEdit
print("Armstrong numbers between 100 and 999:")
for num in range(100, 1000):
s = sum(int(d)**3 for d in str(num))
if s == num:
print(num, end=' ')

Output:

sql
CopyEdit
Armstrong numbers between 100 and 999:
153 370 371 407

8. Class for Bank Account with Deposit and Withdraw


python
CopyEdit
class BankAccount:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance

def deposit(self, amount):


self.balance += amount
print("Deposited:", amount)
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient balance")
else:
self.balance -= amount
print("Withdrawn:", amount)

def display(self):
print(f"Account Holder: {self.name} | Balance:
{self.balance}")

acc = BankAccount("Kiran", 1000)


acc.deposit(500)
acc.withdraw(200)
acc.display()

Output:

yaml
CopyEdit
Deposited: 500
Withdrawn: 200
Account Holder: Kiran | Balance: 1300

9. Program to Merge Two Sorted Lists


python
CopyEdit
a = list(map(int, input("Enter first sorted list: ").split()))
b = list(map(int, input("Enter second sorted list: ").split()))

merged = sorted(a + b)
print("Merged Sorted List:", merged)

Output:

yaml
CopyEdit
Enter first sorted list: 1 3 5
Enter second sorted list: 2 4 6
Merged Sorted List: [1, 2, 3, 4, 5, 6]

10. Generate Pascal’s Triangle


python
CopyEdit
def pascal(n):
for i in range(n):
print(' '*(n-i), end='')
val = 1
for j in range(i+1):
print(val, end=' ')
val = val * (i - j) // (j + 1)
print()

rows = int(input("Enter number of rows: "))


pascal(rows)

Output:

markdown
CopyEdit
Enter number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

11. Student Marksheet with Class


python
CopyEdit
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
self.total = sum(marks)
self.avg = self.total / len(marks)

def display(self):
print(f"Name: {self.name}, Marks: {self.marks}, Total:
{self.total}, Avg: {self.avg:.2f}")

s1 = Student("Arun", [75, 80, 65])


s2 = Student("Deepa", [85, 90, 92])
s1.display()
s2.display()

Output:

yaml
CopyEdit
Name: Arun, Marks: [75, 80, 65], Total: 220, Avg: 73.33
Name: Deepa, Marks: [85, 90, 92], Total: 267, Avg: 89.00

12. Number Pattern (Pyramid)


python
CopyEdit
n = int(input("Enter number of rows: "))
for i in range(1, n+1):
print(' '*(n-i), end='')
for j in range(1, i+1):
print(j, end=' ')
print()

Output:

markdown
CopyEdit
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

You might also like