KEMBAR78
MSC FINAL PYTHON LAB | PDF | Computer Science | Computing
0% found this document useful (0 votes)
46 views22 pages

MSC FINAL PYTHON LAB

Uploaded by

sekar
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)
46 views22 pages

MSC FINAL PYTHON LAB

Uploaded by

sekar
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/ 22

Page no.

1. DATA ITEMS, LISTS, DICTIONARIES AND TUPLES

PROGRAM:

name = "Alice"
age = 30
is_student = False

fruits = ["apple", "banana", "cherry"]


numbers = [1, 2, 3, 4, 5]
person = {"name": name, "age": age, "is_student": is_student}
inventory = {"fruits": fruits, "numbers": numbers}

point = (3, 4)
coordinates = [(1, 2), (5, 6), (7, 8)]
print("Name:", name)

print("Age:", age)
print("Is Student:", is_student)
print("Fruits:", fruits)
print("Numbers:", numbers)
print("Person:", person)
print("Inventory:", inventory)
print("Point:", point)
print("Coordinates:", coordinates)

Department of Computer Science


Page no.

OUTPUT:

Name: Alice
Age: 30
Is Student: False
Fruits: ['apple', 'banana', 'cherry']
Numbers: [1, 2, 3, 4, 5]
Person: {'name': 'Alice', 'age': 30, 'is_student': False}
Inventory: {'fruits': ['apple', 'banana', 'cherry'], 'numbers': [1, 2, 3, 4, 5]}
Point: (3, 4)
Coordinates: [(1, 2), (5, 6), (7, 8)]

Department of Computer Science


Page no.

2. CONDITIONAL BRANCHES
PROGRAM:

score = float(input("Enter the student's score: "))

if 90 <= score <= 100:

grade = 'A'

remarks = 'Excellent'

elif 80 <= score < 90:

grade = 'B'

remarks = 'Very Good'

elif 70 <= score < 80:

grade = 'C'

remarks = 'Good'

elif 60 <= score < 70:

grade = 'D'

remarks = 'Satisfactory'

elif 0 <= score < 60:

grade = 'F'

remarks = 'Fail'

else:

grade = 'Invalid'

remarks = 'Score is out of range (0-100)'

print(f"Grade: {grade}")

print(f"Remarks: {remarks}")

Department of Computer Science


Page no.

OUTPUT:

Enter the student's score: 80

Grade: B

Remarks: Very Good

Enter the student's score: 92

Grade: A

Remarks: Excellent

Enter the student's score: 78.5

Grade: C

Remarks: Good

Enter the student's score: 50

Grade: F

Remarks: Fail

Enter the student's score: 110

Grade: Invalid

Remarks: Score is out of range (0-100)

Department of Computer Science


Page no.

3. LOOPS
PROGRAM:

def is_prime(num):

if num < 2:

return False

for i in range(2, int(num ** 0.5) + 1):

if num % i == 0:

return False

return True

start = int(input("Enter the starting number: "))

end = int(input("Enter the ending number: "))

if start <= 1:

start = 2 # Adjust the start if it's less than 2

print(f"Prime numbers between {start} and {end}:")

for number in range(start, end + 1):

if is_prime(number):

print(number)

Department of Computer Science


Page no.

OUTPUT:
Enter the starting number: 10

Enter the ending number: 30

Prime numbers between 10 and 30:

11

13

17

19

23

29

Department of Computer Science


Page no.

4. FUNCTIONS
PROGRAM:

def calculate_square(number):

return number ** 2

def greet(name, age):

if age < 18:

return f"Hello, {name}! You are under 18 years old."

else:

return f"Hello, {name}! You are {age} years old."

def add_numbers(a, b):

return a + b

def create_person(name, age, is_student):

person_info = {

"Name": name,

"Age": age,

"Is Student": is_student

return person_info

if name == " main ":

# Use the functions to perform various tasks

num = 5

squared = calculate_square(num)

print(f"The square of {num} is {squared}")

person_greeting = greet("Alice", 25)

print(person_greeting)

Department of Computer Science


Page no.

sum_result = add_numbers(10, 20)

print(f"The sum is {sum_result}")

person_data = create_person("Bob", 21, True)

print("Person Information:")

for key, value in person_data.items():

print(f"{key}: {value}")

Department of Computer Science


Page no.

OUTPUT:

The square of 5 is 25

Hello, Alice! You are 25 years old.

The sum is 30

Person Information:

Name: Bob

Age: 21

Is Student: True

Department of Computer Science


Page no.

5. EXCEPTION HANDLING
PROGRAM:

try:

num1 = int(input("Enter a number: "))

num2 = int(input("Enter another number: "))

result = num1 / num2

print("Result:", result)

except ValueError:

print("Please enter valid integers.")

except ZeroDivisionError:

print("Division by zero is not allowed.")

except Exception as e:

print("An error occurred:", e)

else:

print("No exceptions were raised.")

finally:

print("Execution completed.")

Department of Computer Science


Page no.

OUTPUT:

Enter a number: 10

Enter another number: 2

Result: 5.0

No exceptions were raised.

Execution completed.

Department of Computer Science


Page no.

6. INHERITANCE
PROGRAM:

class Animal:

def init (self, name, species):

self.name = name

self.species = species

def speak(self):

print(f"{self.name} makes a sound")

class Dog(Animal):

def speak(self):

print(f"{self.name} barks")

class Cat(Animal):

def speak(self):

print(f"{self.name} meows")

dog = Dog("Buddy", "Dog")

cat = Cat("Whiskers", "Cat")

dog.speak()

cat.speak()

Department of Computer Science


Page no.

OUTPUT:

Buddy barks

Whiskers meows

Department of Computer Science


Page no.

7. POLYMORPHISM
PROGRAM:

import math

class Shape:

def area(self):

pass

class Circle(Shape):

def init (self, radius):

self.radius = radius

def area(self):

return math.pi * self.radius ** 2

class Rectangle(Shape):

def init (self, width, height):

self.width = width

self.height = height

def area(self):

return self.width * self.height

shapes = [Circle(3), Rectangle(4, 5), Circle(2.5)]

for shape in shapes:

print(f"Area: {shape.area():.2f}")

Department of Computer Science


Page no.

OUTPUT:

Area: 28.27

Area: 20.00

Area: 19.63

Department of Computer Science


Page no.

8. IMPLEMENT FILE OPERATIONS


PROGRAM:

with open('sample.txt', 'w') as file:


file.write("Hello, this is a sample text file.\n")
file.write("Python is a versatile programming language.\n")
with open('sample.txt', 'a') as file:
file.write("You can also append text to an existing file.\n")
with open('sample.txt', 'r') as file:
content = file.read()
print("Contents of the file:")
print(content)
with open('sample.txt', 'r') as file:
print("\nReading line by line:")
for line in file:

print(line, end='')
with open('sample.txt', 'r') as file:
lines = file.readlines()
print("\nReading using readlines():")
for line in lines:
print(line, end='')
import os
if os.path.exists('sample.txt'):
os.remove('sample.txt')
print("\nFile 'sample.txt' has been deleted.")
else:
print("\nFile 'sample.txt' does not exist.")

Department of Computer Science


Page no.

OUTPUT:

Contents of the file:

Hello, this is a sample text file.

Python is a versatile programming language.

You can also append text to an existing file.

Reading line by line:

Hello, this is a sample text file.

Python is a versatile programming language.

You can also append text to an existing file.

Reading using readlines():

Hello, this is a sample text file.

Python is a versatile programming language.

You can also append text to an existing file.

File 'sample.txt' has been deleted.

Department of Computer Science


Page no.

9. MODULES
PROGRAM:

# my_module.py

def greet(name):

return f"Hello, {name}!"

def multiply(x, y):

return x * y

def subtract(a, b):

return a - b

def divide(a, b):

if b == 0:

return "Error: Division by zero"

return a / b

# main.py

import my_module

name = "Alice"

greeting = my_module.greet(name)

print(greeting)

result = my_module.multiply(3, 5)

print(result)

result = my_module.subtract(10, 3)

print(result)

result = my_module.divide(8, 2)

print(result)

Department of Computer Science


Page no.

OUTPUT:

Hello, Alice!

15

4.0

Department of Computer Science


Page no.

10. CREATING DYNAMIC AND INTERACTIVE WEBPAGES USING


FORMS
PROGRAM:

#python
from flask import Flask, render_template
app = Flask( name )
@app.route('/')
def index():
return render_template('index.html')
if name == ' main ':
app.run(debug=True)

#html
<!DOCTYPE html>
<html>
<head>

<title>Dynamic Webpage with Clock</title>


</head>
<body>

<h1>Interactive Webpage</h1>
<p>Current time: <span id="clock">Loading...</span></p>
<script>

function updateClock() {
const clockElement = document.getElementById('clock');
const now = new Date();
const timeString = now.toLocaleTimeString();
clockElement.textContent = timeString;

Department of Computer Science


Page no.

}
setInterval(updateClock, 1000);
updateClock();

</script>
</body>

</html>

Department of Computer Science


Page no.

OUTPUT:

Department of Computer Science

You might also like