0% found this document useful (0 votes)
7 views26 pages

Python Labb 2

The document outlines various Python programming exercises focusing on basic data structures, conditional statements, loops, functions, exception handling, inheritance, polymorphism, file operations, and built-in modules. Each exercise includes an aim, algorithm, coding examples, and sample input/output to demonstrate the functionality of the code. The results confirm that all programs were verified and executed successfully.

Uploaded by

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

Python Labb 2

The document outlines various Python programming exercises focusing on basic data structures, conditional statements, loops, functions, exception handling, inheritance, polymorphism, file operations, and built-in modules. Each exercise includes an aim, algorithm, coding examples, and sample input/output to demonstrate the functionality of the code. The results confirm that all programs were verified and executed successfully.

Uploaded by

priyacs104
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

EX.

NO: 01
PROGRAMS USING ELEMENTARY DATA ITEMS, LISTS,
DATE: DICTIONARIES AND TUPLES

AIM
To implement basic operations on list, set, tuple, and dictionary in Python.

ALGORITHM

1. Start the program.


2. Create an empty list, insert elements (append), delete element (pop), and display.
3. Create an empty set, insert elements (add), delete element (remove), and display.
4. Convert the list into a tuple and display (immutable).
5. Create a dictionary, add key-value pairs, delete a pair, and display.
6. End the program.

CODING

# List
l = []

# Adding elements into list


[Link](5)
[Link](10)
print("Adding 5 and 10 in list:", l)

# Popping element from list


[Link]()

1
print("Popped one element from list:", l)
print()
# Set
s = set()

# Adding elements into set


[Link](5)
[Link](10)
print("Adding 5 and 10 in set:", s)

# Removing element from set


[Link](5)
print("Removing 5 from set:", s)
print()
# Tuple (created from list)
t = tuple(l)
print("Tuple :", t)
print()
# Dictionary
d = {}
# Adding key-value pairs
d[5] = "Five"
d[10] = "Ten"
print("Dictionary after adding elements:", d)
# Removing key-value pair
del d[10]
print("Dictionary after deleting key 10:", d)

2
SAMPLE INPUT / OUTPUT:
Adding 5 and 10 in list: [5, 10]
Popped one element from list: [5]

Adding 5 and 10 in set: {10, 5}


Removing 5 from set: {10}

Tuple : (5,)

Dictionary after adding elements: {5: 'Five', 10: 'Ten'}


Dictionary after deleting key 10: {5: 'Five'}

RESULT:

Thus the above program is verified and executed successfully.

3
EX. NO: 02
PROGRAMS USING CONDITIONAL BRANCHES
DATE:

AIM

To implement decision-making statements (if, if-else, if-elif-else) in Python.

ALGORITHM

1. Start the program.

2. For if: take input, check condition, print message.

3. For if-else: take input, check condition, print either true-part or else-part.

4. For if-elif-else: take input, check multiple conditions, print respective message or default.

5. End the program.

If Statement

CODING
name = input("Enter Name: ")

if name == "MASC":
print("WELCOME MASC")
print("WELCOME GUEST!!!")

SAMPLE INPUT / OUTPUT:


Enter Name: MASC
WELCOME MASC
WELCOME GUEST!!!
If Else Statement
4
CODING
name = input('Enter Name : ')

if name == 'MASC':
print('Hello MASC! Good Morning')
else:
print('Hello Guest! Good Morning')

SAMPLE INPUT / OUTPUT:

Enter Name : MASC


Hello MASC! Good Morning

If – Elif - Else Statement

CODING
brand = input("Enter Your Favourite Brand: ")

if brand == "RC":
print("It is children's brand")
elif brand == "KF":
print("It is not that much kick")
elif brand == "FO":
print("Buy one get Free One")
else:
print("Other Brands are not recommended")

5
SAMPLE INPUT / OUTPUT:

Enter Your Favourite Brand: KF

It is not that much kick

RESULT:

Thus the above program is verified and executed successfully.

6
EX. NO: 03
PROGRAM USING LOOP
DATE:

While Loop

AIM
To write a Python program that calculates the sum of the first n natural numbers using a
while loop.

ALGORITHM

1. Start.
2. Input a number n from the user.
3. Initialize a variable sum to 0.
4. Initialize a variable i to 1.
5. Use a while loop that runs while i <= n.
 Add i to sum.
 Increment i by 1.
6. After the loop ends, print the total sum.
7. Stop.

CODING

n = int(input("Enter number: "))


sum = 0
i=1
while i <= n:
sum = sum + i
i=i+1
print("The sum of first", n, "numbers is:", sum)

7
SAMPLE INPUT / OUTPUT:

Enter number: 10
The sum of first 10 numbers is: 55

For Loop

AIM

To write a Python program that prints each character of a string along with its index using
a for loop.

ALGORITHM

1. Start.
2. Input a string s from the user.
3. Initialize a variable i to 0.
4. Use a for loop to iterate through each character x in the string s.
a. Print the character x and its index i.
b. Increment i by 1.
5. Repeat until all characters are processed.
6. Stop.

CODING

s = input("Enter some String: ")


i=0

for x in s:
print("The character present at", i, "index is:", x)
i=i+1

SAMPLE INPUT / OUTPUT:

8
Enter some String: KARTHIK
The character present at 0 index is: K
The character present at 1 index is: A
The character present at 2 index is: R
The character present at 3 index is: T
The character present at 4 index is: H
The character present at 5 index is: I
The character present at 6 index is: K

RESULT:

Thus the above program is verified and executed successfully.

EX. NO: 04

9
DATE: PROGRAM USING FUNCTIONS

AIM

To find the factorial of a number using a recursive function in Python.

ALGORITHM

1. Start the program.

2. Define a function recur_factorial(n) that:

 Returns 1 if n == 1.
 Otherwise returns n recur_factorial(n-1).

3. Input a number num.

4. If num 0, display factorial does not exist.

5. Else if num = 0, display factorial of O is 1.

6. Else, call recur_factorial(num) and print the result.

7. End the program.

CODING

def recur_factorial(n):
if n == 1:
return n
else:
return n * recur_factorial(n - 1)
# Take input from the user
num = int(input("Enter a number: "))
# Check if the number is negative
if num < 0:

10
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

SAMPLE INPUT / OUTPUT:

Enter a number: 5
The factorial of 5 is 120

RESULT:

Thus above program is verified and executed successfully.

EX. NO: 05

11
DATE: PROGRAMS USING EXCEPTION HANDLING

AIM
To demonstrate handling of multiple exceptions using a single program in Python.

ALGORITHM

1. Start the program.


2. Define function fun(a):
 If a 4, compute b = a / (a-3) (may raise ZeroDivisionError).
 If a >= 4, print value of b (may raise NameError).

3. Use a try block to call fun (3) and fun(5).


4. Use except blocks to handle:
 ZeroDivisionError print - error message.
 NameError - print error message.

5. End the program.

CODING

# Program to handle multiple errors with one except statement


def fun(a):
if a < 4:
# Throws ZeroDivisionError for a = 3
b = a / (a - 3)
else:
# Throws NameError for a >= 4 because 'b' is not defined
print("Value of b =", b)
try:
fun(3)

12
fun(5)
# Handling multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

SAMPLE INPUT / OUTPUT:

ZeroDivisionError Occurred and Handled

RESULT:
Thus the above program is verified and executed successfully.

13
EX. NO: 06
PROGRAMS USING INHERITANCE
DATE:

AIM
To demonstrate inheritance in Python using base and derived classes.

ALGORITHM
1. Start the program.
2. Define a base class Person
 Constructor to initialize name.
 Method getName() returns name.
 Method isEmployee() returns False.
3. Define a derived class Employee (Person):
 Override isEmployee() returns True.
4. Create an object of Person and display name with employee status.
5. Create an object of Employee and display name with emplo 'atus.
6. End the program.

CODING
# A Python program to demonstrate inheritance

# Base or Super class


# Note: In Python 3, class Person is implicitly derived from object
class Person(object):
# Constructor
def __init__(self, name):
[Link] = name

14
# To get name
def getName(self):
return [Link]
# To check if this person is an employee
def isEmployee(self):
return False
# Inherited or Subclass
class Employee(Person):
# Overriding the isEmployee method
def isEmployee(self):
return True
# Driver code
emp = Person("AAAAA") # An Object of Person
print([Link](), [Link]()) # Output: AAAAA False
emp = Employee("BBBBB") # An Object of Employee
print([Link](), [Link]()) # Output: BBBBB True

SAMPLE INPUT / OUTPUT:


AAAAA False
BBBBB True

RESULT:

Thus the above program is verified and executed successfully.

15
EX. NO: 07
PROGRAMS USING POLYMORPHISM
DATE:

AIM
To demonstrate polymorphism in Python using classes and common methods.

ALGORITHM

1. Start the program.


2. Define class India with methods: capital(),
 language(), type().
3. Define class USA with same methods:
 capital(), language(), type().
4. Create objects obj_ind (India) and obj_usa (USA).
5. Use a loop to call capital(), language(), and type() for both objects.
6. End the program.

CODING

# Class for India


class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
# Class for USA
class USA():

16
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
# Creating objects
obj_ind = India()
obj_usa = USA()
# Looping through both objects to demonstrate polymorphism
for country in (obj_ind, obj_usa):
[Link]()
[Link]()
[Link]()
print() # Add a blank line for clarity

SAMPLE INPUT / OUTPUT:

New Delhi is the capital of India.


Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

RESULT:

Thus the above program is verified and executed successfully.

17
EX. NO: 08
PROGRAMS TO IMPLEMENT FILE OPERATIONS
DATE:

AIM

To perform file operations in Python: create, read, append, rename, and delete a file.

ALGORITHM

1. Start the program.

2. Create file: open in write mode, write text, handle errors.

3. Read file: open in read mode, display content, handle errors.

4. Append file: open in append mode, add text, handle errors.

5. Rename file: use [Link](), handle errors.

6. Delete file: use [Link](), handle errors.

7. Call functions in sequence and display messages.

8. End the program.

CODING

import os
def create_file(filename):
try:
with open(filename, 'w') as f:
[Link]('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)

18
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = [Link]()
print(contents)
except IOError:
print("Error: could not read file " + filename)

def append_file(filename, text):


try:
with open(filename, 'a') as f:
[Link](text)
print("Text appended to file " + filename + " successfully.")
except IOError:
print("Error: could not append to file " + filename)

def rename_file(filename, new_filename):


try:
[Link](filename, new_filename)
print("File " + filename + " renamed to " + new_filename + " successfully.")
except OSError:
print("Error: could not rename file " + filename)

def delete_file(filename):
try:
[Link](filename)
print("File " + filename + " deleted successfully.")
except OSError:

19
print("Error: could not delete file " + filename)
# Entry point of the script
if __name__ == "__main__":
filename = "[Link]"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)

SAMPLE INPUT / OUTPUT:

File [Link] created successfully.


Hello, world!
Text appended to file [Link] successfully.
Hello, world!
This is some additional text.
File [Link] renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.

RESULT:
Thus the above program is verified and executed successfully.

20
EX. NO: 09
PROGRAMS USING MODULES
DATE:

AIM
To demonstrate Python built-in modules: math, random, datetime, and time.

ALGORITHM

1. Import required modules: math, random, datetime, time.


2. Math: perform sqrt, pi, degrees, radians, sin, cos, tan, factorial.
3. Random: generate random integers, floats, and choose from a list.
4. Datetime & Time: get current seconds ([Link]) and convert to date ([Link]).
5. Display results.
6. End the program.

CODING

# Importing built-in module math


import math
# Using square root (sqrt) function
print("Square root of 25:", [Link](25))
# Using pi constant
print("Value of pi:", [Link])
# Converting 2 radians to degrees
print("2 radians in degrees:", [Link](2))
# Converting 60 degrees to radians
print("60 degrees in radians:", [Link](60))
# Trigonometric functions
print("Sine of 2 radians:", [Link](2))

21
print("Cosine of 0.5 radians:", [Link](0.5))
print("Tangent of 0.23 radians:", [Link](0.23))
# Factorial of 4
print("Factorial of 4:", [Link](4))
# Importing built-in module random
import random
# Printing a random integer between 0 and 5
print("Random integer between 0 and 5:", [Link](0, 5))
# Printing a random floating-point number between 0 and 1
print("Random float between 0 and 1:", [Link]())
# Random number between 0 and 100
print("Random float between 0 and 100:", [Link]() * 100)
# Choosing a random element from a list
List = [1, 4, True, 800, "python", 27, "hello"]
print("Random choice from list:", [Link](List))
# Importing built-in modules datetime and time
import time
from datetime import date
# Returns the number of seconds since the Unix Epoch (January 1, 1970)
print("Seconds since Unix Epoch:", [Link]())
# Converts seconds to a date
print("Date from timestamp 454554:", [Link](454554))

SAMPLE INPUT/OUTPUT:

Square root of 25: 5.0


Value of pi: 3.141592653589793
2 radians in degrees: 114.59155902616465
60 degrees in radians: 1.0471975511965976

22
Sine of 2 radians: 0.9092974268256817
Cosine of 0.5 radians: 0.8775825618903728
Tangent of 0.23 radians: 0.23414336235146527
Factorial of 4: 24
Random integer between 0 and 5: 3
Random float between 0 and 1: 0.43927354743222524
Random float between 0 and 100: 93.86472892418928
Random choice from list: python
Seconds since Unix Epoch: 1759279981.2113142
Date from timestamp 454554: 1970-01-06

RESULT:

Thus the above program is verified and executed successfully.

23
EX. NO: 10
PROGRAMS FOR CREATING DYNAMIC AND INTERACTIVE
DATE: WEB PAGES USING FORMS

AIM
To take user input and display a welcome message using HTML and JavaScript.

ALGORITHM

1. Create HTML page with input field, button, and paragraph for output.

2. Write EnterName() function in JavaScript:

 Get input value.


 Display "Welcome to <name>" in paragraph.

3. Link button onclick to EnterName().

4. End the program.

CODING

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MASC</title>
</head>
<body>
<h1>Enter Your Name</h1>

<input id="name" type="text" placeholder="Your name here">


<button type="button" onclick="EnterName()">Submit</button>

24
<p style="color:green" id="demo"></p>
<script>
function EnterName() {
let x = [Link]("name").value;
[Link]("demo").innerHTML = "Welcome to " + x;
}
</script>
</body>
</html>

SAMPLE INPUT/OUTPUT:

25
RESULT:

Thus the above program is verified and executed successfully.

26

You might also like