0% found this document useful (0 votes)
3 views14 pages

Python Lab

The document outlines multiple Python programs demonstrating various programming concepts such as conditional statements, looping constructs, data structures (list, tuple, set, dictionary), functions, classes, and file handling. Each program includes an aim, algorithm, code implementation, output, and a result statement confirming successful execution. The examples illustrate practical applications of these concepts in a structured manner.

Uploaded by

kishore29007
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)
3 views14 pages

Python Lab

The document outlines multiple Python programs demonstrating various programming concepts such as conditional statements, looping constructs, data structures (list, tuple, set, dictionary), functions, classes, and file handling. Each program includes an aim, algorithm, code implementation, output, and a result statement confirming successful execution. The examples illustrate practical applications of these concepts in a structured manner.

Uploaded by

kishore29007
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

EX.

NO : 1 PROGRAMS USING CONDITIONAL AND LOOPING CONSTRUCTS

DATE :

AIM :

The aim of this program is to illustrate the application of conditional and looping constructs
(specifically if/else statements and for loops) in programming logic.

ALGORITHM:

Step 1: Start
Step 2: Assign value 14 to the variable hour
Step 3: If hour < 12, print “Good morning!”
Else if hour < 18, print “Good afternoon!”
Else, print “Good evening!”
Step 4: Create a list numbers = [1, 2, 3, 4, 5, 6]
Step 5: For each number in the list numbers
a) If the number is divisible by 2, print “number is even”
b) Else, print “number is odd”
Step 6: Initialize count = 5
Step 7: While count > 0
a) Print the value of count
b) Decrease count by 1
Step 8: Print “Lift off!”
Step 9: For i from 1 to 3
For j from 1 to 3
a) Calculate product = i × j
b) Print the multiplication result in tabular form
Step 10: Stop
PROGRAM:

hour = 14 # 2 PM

if hour < 12:

print("Good morning!")

elif hour < 18:

print("Good afternoon!")

else:

print("Good evening!")

numbers = [1, 2, 3, 4, 5, 6]

for num in numbers:

if num % 2 == 0:

print(f"{num} is even")

else:

print(f"{num} is odd")

count = 5

while count > 0:

print(f"Counting down: {count}")

count = count - 1

print("Lift off!")

for i in range(1, 4):

for j in range(1, 4):

product = i * j

print(f"{i} * {j} = {product}", end="\t")

print()
OUTPUT:

Good afternoon!

1 is odd

2 is even

3 is odd

4 is even

5 is odd

6 is even

Counting down: 5

Counting down: 4

Counting down: 3

Counting down: 2

Counting down: 1

Lift off!

1*1=1 1*2=2 1*3=3

2*1=2 2*2=4 2*3=6

3*1=3 3*2=6 3*3=9

RESULT

Thus, the Python program using conditional statements (if, if-else, elseif) and looping constructs
(for loop and while loop) was executed successfully.
[Link] : 2

PROGRAM USING DIFFERENT DATA FRAMES LIKE LIST,TUPLE,SET,DICTIONARY

DATE :

AIM

To demonstrate the use of Python’s built-in data structures—List, Tuple, Set, and Dictionary—
and perform basic operations such as accessing, modifying, adding, removing, and iterating over
elements.

ALGORITHM:

1. Start the program.


2. List Operations

 Create a list of fruits with some duplicate values.

 Display the initial list.

 Access and display the first element using its index.

 Modify one element in the list.

 Add a new element to the list using append().

 Display the updated list.

3. Tuple Operations

 Create a tuple representing coordinates.

 Display the tuple.

 Access and display individual elements of the tuple.

 Explain that tuples are immutable and cannot be modified.

4. Set Operations

 Create a set of colors containing duplicate values.

 Display the set (duplicates removed automatically).

 Add a new element to the set.


 Remove an existing element from the set.

 Display the updated set.

5. Dictionary Operations

 Create a dictionary containing personal details.

 Display the dictionary.

 Access and display a value using its key.

 Modify an existing key’s value.

 Add a new key-value pair to the dictionary.

 Display the updated dictionary

6. Iteration

 Iterate through the dictionary using a loop.

 Display each key and its corresponding value.

7. End the program.

PROGRAM:

print("--- Lists ---")

fruit_list = ["Apple", "Banana", "Cherry", "Apple"]

print(f"Initial list: {fruit_list}")

print(f"First item: {fruit_list[0]}")

fruit_list[1] = "Blueberry"

print(f"Modified list: {fruit_list}")

fruit_list.append("Dragonfruit")

print(f"List after adding an item: {fruit_list}\n")

print("--- Tuples ---")

coordinates = (10.0, 20.5)


print(f"Coordinates tuple: {coordinates}")

print(f"Latitude: {coordinates[0]}, Longitude: {coordinates[1]}")

print("Tuples are immutable; they cannot be changed after creation.\n")

print("--- Sets ---")

colors_set = {"Red", "Green", "Blue", "Red"} # Duplicate "Red" is automatically ignored

print(f"Initial set (duplicates removed): {colors_set}")

colors_set.add("Yellow")

print(f"Set after adding 'Yellow': {colors_set}")

colors_set.remove("Green")

print(f"Set after removing 'Green': {colors_set}\n")

print("--- Dictionaries ---")

person_dict = {

"name": "Alice",

"age": 30,

"city": "New York"

print(f"Initial dictionary: {person_dict}")

print(f"Person's name: {person_dict['name']}")

person_dict["age"] = 31

print(f"Modified dictionary: {person_dict}")

person_dict["email"] = "alice@[Link]"

print(f"Dictionary after adding email: {person_dict}\n")

print("Iterating through the dictionary:")

for key, value in person_dict.items():

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

--- Lists ---

Initial list: ['Apple', 'Banana', 'Cherry', 'Apple']

First item: Apple

Modified list: ['Apple', 'Blueberry', 'Cherry', 'Apple']

List after adding an item: ['Apple', 'Blueberry', 'Cherry', 'Apple', 'Dragonfruit']

--- Tuples ---

Coordinates tuple: (10.0, 20.5)

Latitude: 10.0, Longitude: 20.5

Tuples are immutable; they cannot be changed after creation.

--- Sets ---

Initial set (duplicates removed): {'Red', 'Blue', 'Green'}

Set after adding 'Yellow': {'Yellow', 'Red', 'Blue', 'Green'}

Set after removing 'Green': {'Yellow', 'Red', 'Blue'}

--- Dictionaries ---

Initial dictionary: {'name': 'Alice', 'age': 30, 'city': 'New York'}

Person's name: Alice

Modified dictionary: {'name': 'Alice', 'age': 31, 'city': 'New York'}

Dictionary after adding email: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email':
'alice@[Link]'}

Iterating through the dictionary:

name: Alice

age: 31

city: New York

email: alice@[Link]
RESULT:

Thus, the Python program demonstrating different data frames using List, Tuple, Set and
Dictionary was executed successfully.
EX NO : 3 PROGRAM USING FUNCTION AND CLASSES

DATE :

AIM:

To develop a Python program to simulate a simple bank account system that allows the user to
deposit money, withdraw money, and check the account balance using a menu-driven approach.

ALGORITHM :

Step 1 : Start

Step 2 : Enter the account holder name.

Step 3 : Create a bank account with initial balance = 1000.

Step 4 : Display the menu options (Deposit, Withdraw, Check Balance, Exit).

Step 5 :Enter the user choice.

Step 6 : If choice = Deposit, enter amount and add it to balance.

Step 7 :If choice = Withdraw, enter amount and subtract it from balance if balance is sufficient.

Step 8 : If choice = Check Balance, display the current balance.

Step 9 : If choice = Exit, stop the program.

Step 10 : Repeat steps 4–9 until the user exits.

Step 11: End.

PROGRAM:

def show_menu():

print("\n--- Bank Menu ---")

print("1. Deposit")

print("2. Withdraw")

print("3. Check Balance")


print("4. Exit")

class BankAccount:

def __init__(self, owner, balance=0):

[Link] = owner

[Link] = balance

def deposit(self, amount):

[Link] += amount

print(f"Deposited: {amount}")

print(f"New Balance: {[Link]}")

def withdraw(self, amount):

if amount > [Link]:

print("Insufficient balance!")

else:

[Link] -= amount

print(f"Withdrawn: {amount}")

print(f"Remaining Balance: {[Link]}")

def check_balance(self):

print(f"Current Balance: {[Link]}")

def main():

name = input("Enter account holder name: ")

account = BankAccount(name, 1000)

while True:

show_menu()
choice = int(input("Enter your choice: "))

if choice == 1:

amount = float(input("Enter deposit amount: "))

[Link](amount)

elif choice == 2:

amount = float(input("Enter withdrawal amount: "))

[Link](amount)

elif choice == 3:

account.check_balance()

elif choice == 4:

print("Thank you for using the bank system!")

break

else:

print("Invalid choice!")

main()

OUTPUT:

Enter account holder name: raj kumar

--- Bank Menu ---

1. Deposit

2. Withdraw

3. Check Balance
4. Exit

Enter your choice: 1

Enter deposit amount: 500

Deposited: 500.0

New Balance: 1500.0

RESULT :

The program was executed successfully, allowing the user to deposit money, withdraw money,
and check the account balance through a menu-driven bank account system.
EX NO : 4 PROGRAM USING STRING AND FILES

DATE :

AIM

To write a Python program to accept a string from the user, write it into a file, and
read the content from the file.
ALGORITHM:

Step 1 : Start

Step 2 :Enter a string from the user.

Step 3 : Open a file [Link] in write mode.

Step 4 : Write the string into the file.

Step 5 : Close the file.

Step 6 : Open the file [Link] in read mode.

Step 7 : Read the content of the file.

Step 8 : Display the content on the screen.

Step 9 : Close the file.

Step 10 : Stop

PROGRAM :

text = input("Enter a string: ")

file = open("[Link]", "w")

[Link](text)

[Link]()

file = open("[Link]", "r")

content = [Link]()
print("Content in file:", content)

[Link]()

OUTPUT:

Enter a string: Hello Python

Content in file: Hello Python

RESULT:

The program was executed successfully, and the entered string was written to the
file and read back from the file and displayed on the screen.

You might also like