0% found this document useful (0 votes)
28 views

Python Lab Manual

Uploaded by

gohade3474
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Python Lab Manual

Uploaded by

gohade3474
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

CM-507

PYTHON PROGRAMMING LAB


1. Write and execute simple python Program.

n = int(input("Enter a positive integer: "))


for i in range(1, n+1):
print(i)

2. Write /execute simple ‘Python’ program: Develop minimum 2 programs using different data types (numbers,
string, tuple, list, and dictionary).

Program1: Using numbers

a=5
b=3

c=a+b
print("Sum of", a, "and", b, "is", c)

d=a-b
print("Difference of", a, "and", b, "is", d)

e=a*b
print("Product of", a, "and", b, "is", e)

f=a/b
print("Quotient of", a, "and", b, "is", f)p

Program2: Using strings

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

greeting = "Hello, what fruit would you like to have?"


print(greeting)

for fruit in fruits:


print(fruit)

selected_fruit = input("Enter the name of the fruit you would like to have: ")

if selected_fruit in fruits:
print("You have selected", selected_fruit)
else:
print("Sorry, we don't have", selected_fruit)

3. Write /execute simple ‘Python’ program: Develop minimum 2 programs using Arithmetic Operators,
exhibiting data type conversion.
Program1: Using Arithmetic Operators

a=5
b=3

c=a+b
print("Sum of", a, "and", b, "is", c)

d=a-b
print("Difference of", a, "and", b, "is", d)

e=a*b
print("Product of", a, "and", b, "is", e)

f=a/b
print("Quotient of", a, "and", b, "is", f)

g = int(a / b)
print("Integer Quotient of", a, "and", b, "is", g)

Program2: Using Data type conversion

# Converting an integer to a string


integer = 42
string = str(integer)
print("String:", string)

# Converting a string to an integer


string = "42"
integer = int(string)
print("Integer:", integer)

# Converting a float to a string


float_num = 3.14
string = str(float_num)
print("String:", string)

# Converting a string to a float


string = "3.14"
float_num = float(string)
print("Float:", float_num)

# Converting a list to a tuple


lst = [1, 2, 3, 4]
tuple = tuple(lst)
print("Tuple:", tuple)

# Converting a tuple to a list


tuple = (1, 2, 3, 4)
lst = list(tuple)
print("List:", lst)

4. (i)Write simple programs to convert U.S. dollars to Indian rupees.


Program:

usd = float(input("Enter currency in USD: "))


inr = usd * 73

print("The currency in INR is",round(inr,2))

(ii) Write simple programs to convert bits to Megabytes, Gigabytes and Terabytes.

# Python implementation of above program

# Function to calculates the bits


def Bits(kilobytes) :

# calculates Bits
# 1 kilobytes(s) = 8192 bits
Bits = kilobytes * 8192

return Bits

# Function to calculates the bytes


def Bytes(kilobytes) :

# calculates Bytes
# 1 KB = 1024 bytes
Bytes = kilobytes * 1024

return Bytes

# Driver code
if __name__ == "__main__" :

kilobytes = 1

print(kilobytes, "Kilobytes =",


Bytes(kilobytes) , "Bytes and",
Bits(kilobytes), "Bits")
5. Write simple programs to calculate the area and perimeter of the square, and the volume & perimeter of the
cone.

import math
pi = math.pi

# Function to calculate Volume of Cone


def volume(r, h):
return (1 / 3) * pi * r * r * h

# Function To Calculate Surface Area of Cone


def surfacearea(r, s):
return pi * r * s + pi * r * r

# Driver Code
radius = float(5)
height = float(12)
slat_height = float(13)
print( "Volume Of Cone : ", volume(radius, height) )
print( "Surface Area Of Cone : ", surfacearea(radius, slat_height) )

6. Write program to: (i) determine whether a given number is odd or even. (ii) Find the greatest of the three
numbers using conditional operators.

def odd_even(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"

def find_greatest(a, b, c):


greatest = a
if b > greatest:
greatest = b
if c > greatest:
greatest = c
return greatest

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


print("The number is", odd_even(num))

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


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print("The greatest number is", find_greatest(a, b, c))

7. Write a program to: i) Find factorial of a given number. ii) Generate multiplication table up to 10 for numbers
1 to 5.

def factorial(num):
if num == 0:
return 1
return num * factorial(num - 1)

def multiplication_table(n):
for i in range(1, 11):
print(n, "x", i, "=", n * i)

num = int(input("Enter a number to find the factorial: "))


print("The factorial of", num, "is", factorial(num))

for i in range(1, 6):


print("\nMultiplication table for", i)
multiplication_table(i)

8. Write a program to: i) Find factorial of a given number. ii) Generate multiplication table up to 10 for numbers
1 to 5 using functions.

def factorial(num):
if num == 0:
return 1
return num * factorial(num - 1)

def multiplication_table(n):
for i in range(1, 11):
print(n, "x", i, "=", n*i)

num = int(input("Enter a number to find the factorial: "))


print("The factorial of", num, "is", factorial(num))

print("\nMultiplication table:")
for i in range(1, 6):
print("Table for", i)
multiplication_table(i)
print("\n")
9. Write a program to: i) Find factorial of a given number using recursion. ii) Generate Fibonacci sequence up to
100 using recursion.

def factorial(num):
if num == 0:
return 1
return num * factorial(num - 1)

def fibonacci(num):
if num <= 1:
return num
return fibonacci(num - 1) + fibonacci(num - 2)

num = int(input("Enter a number to find the factorial: "))


print("The factorial of", num, "is", factorial(num))

print("\nFibonacci sequence:")
for i in range(100):
fib = fibonacci(i)
if fib > 100:
break
print(fib, end=", ")
10. Write a program to: Create a list, add element to list, delete element from the lists.

my_list = []

def add_to_list(element):
my_list.append(element)
print(element, "added to the list")

def delete_from_list(element):
if element in my_list:
my_list.remove(element)
print(element, "deleted from the list")
else:
print(element, "not found in the list")

print("1. Add element to the list")


print("2. Delete element from the list")
print("3. Display the list")
print("4. Quit")
while True:
choice = int(input("Enter your choice: "))

if choice == 1:
element = int(input("Enter an integer to add: "))
add_to_list(element)
elif choice == 2:
element = int(input("Enter an integer to delete: "))
delete_from_list(element)
elif choice == 3:
print("The list contains:", my_list)
elif choice == 4:
print("Exiting the program...")
break
else:
print("Invalid choice. Try again.")
11. Write a program to: Sort the list, reverse the list and counting elements in a list.

my_list = [3, 4, 1, 7, 5, 9, 2, 8, 6, 0]

def sort_list(lst):
return sorted(lst)

def reverse_list(lst):
return lst[::-1]

def count_elements(lst):
count = {}
for element in lst:
count[element] = count.get(element, 0) + 1
return count

print("Original list:", my_list)

sorted_list = sort_list(my_list)
print("Sorted list:", sorted_list)

reversed_list = reverse_list(my_list)
print("Reversed list:", reversed_list)

count = count_elements(my_list)
print("Count of elements in the list:", count)

12. Write a program to: Create dictionary, add element to dictionary, delete element from the dictionary.

my_dict = {'a': 1, 'b': 2, 'c': 3}

def add_element(d, key, value):


d[key] = value
return d
def delete_element(d, key):
if key in d:
del d[key]
return d

print("Original dictionary:", my_dict)

my_dict = add_element(my_dict, 'd', 4)


print("Dictionary after adding an element:", my_dict)

my_dict = delete_element(my_dict, 'a')


print("Dictionary after deleting an element:", my_dict)
13. Write a program to: To calculate average, mean, median, and standard deviation of numbers in a list.

import statistics

numbers = [3, 4, 1, 7, 5, 9, 2, 8, 6, 0]

def average(lst):
return sum(lst) / len(lst)

def mean(lst):
return statistics.mean(lst)

def median(lst):
return statistics.median(lst)

def standard_deviation(lst):
return statistics.stdev(lst)

print("Numbers:", numbers)

avg = average(numbers)
print("Average:", avg)

mn = mean(numbers)
print("Mean:", mn)

md = median(numbers)
print("Median:", md)

stddev = standard_deviation(numbers)
print("Standard Deviation:", stddev)

14. Write a program to: To print Factors of a given Number.

def factors(n):
for i in range(1, n + 1):
if n % i == 0:
print(i)

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


print("Factors of", num, "are:")
factors(num)
15. File Input/output: Write a program to: i) To create simple file and write “Hello World” in it. ii) To open a file
in write mode and append Hello world at the end of a file.

# Step 1: Create a file and write "Hello World" in it


with open("hello.txt", "w") as file:
file.write("Hello World\n")
print("File 'hello.txt' created and written successfully.")

# Step 2: Open the file in append mode and append "Hello World" at the end
with open("hello.txt", "a") as file:
file.write("Hello World\n")
print("File 'hello.txt' appended successfully.")

16. Write a program to :i) To open a file in read mode and write its contents to another file but replace every
occurrence of character ‘h’ ii) To open a file in read mode and print the number of occurrences of a
character ‘a’.

# Step 1: Open a file in read mode and write its contents to another file with 'h' replaced
with open("input.txt", "r") as file1, open("output.txt", "w") as file2:
for line in file1:
modified_line = line.replace('h', 'X') # Replace 'h' with 'X'
file2.write(modified_line)
print("Contents of 'input.txt' copied to 'output.txt' with 'h' replaced.")

# Step 2: Open a file in read mode and count the number of occurrences of 'a'
char_to_count = 'a'
count = 0
with open("input.txt", "r") as file:
for line in file:
count += line.count(char_to_count) # Count occurrences of 'a' in each line
print(f"Number of occurrences of '{char_to_count}' in 'input.txt': {count}")

17. Write a Program to: Add two complex number using classes and objects.

class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag

def __add__(self, other):


real_sum = self.real + other.real
imag_sum = self.imag + other.imag
return ComplexNumber(real_sum, imag_sum)

def display(self):
print(f"Sum: {self.real} + {self.imag}i")

# Input complex numbers


real1 = float(input("Enter real part of the first complex number: "))
imag1 = float(input("Enter imaginary part of the first complex number: "))
real2 = float(input("Enter real part of the second complex number: "))
imag2 = float(input("Enter imaginary part of the second complex number: "))

# Create ComplexNumber objects


complex1 = ComplexNumber(1, 1)
complex2 = ComplexNumber(2, 2)

# Add two complex numbers


result = complex1 + complex2

# Display the result


result.display()

18.Write a Program to: Subtract two complex number using classes and objects.

class ComplexNumber:

def __init__(self, real, imaginary):


self.real = real
self.imaginary = imaginary

def __sub__(self, other):


return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)

def __repr__(self):
return f"({self.real}+{self.imaginary}j)"

def main():
c1 = ComplexNumber(1, 2)
c2 = ComplexNumber(3, 4)

c3 = c1 - c2

print(c3)

if __name__ == "__main__":
main()

19.Write a Program to: Create a package and accessing a package.

# Create a package
package = __import__("my_package")

# Import a module from the package


module = package.my_module

# Call a function from the module


module.my_function()

Procedure:

1. Launch the IDLE application.

2. Open a new file or an existing one, then write your Python code in the editor.

3. Save your file with a `.py` extension.

4. Press F5 or go to the "Run" menu and select "Run Module."


5. Your program's output will appear in the IDLE Shell window.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy