0% found this document useful (0 votes)
18 views17 pages

Python Lab Manual

The document is a lab manual for an Applied Python Programming course at Kakatiya Institute of Technology and Science for Women. It includes various experiments covering Python basics, functions, matrix operations using numpy, data analysis with scipy and matplotlib, and string manipulation. Each experiment is accompanied by code examples and expected outputs.

Uploaded by

bsoundarya66
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)
18 views17 pages

Python Lab Manual

The document is a lab manual for an Applied Python Programming course at Kakatiya Institute of Technology and Science for Women. It includes various experiments covering Python basics, functions, matrix operations using numpy, data analysis with scipy and matplotlib, and string manipulation. Each experiment is accompanied by code examples and expected outputs.

Uploaded by

bsoundarya66
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

KAKATIYA INSTITUTE OF TECHNOLOGY AND SCIENCE FOR WOMEN

MANIK BHANDAR, NIZAMABAD


APPLIED PYTHON PROGRAMMING LAB MANUAL
ECE I-II SEM
LIST OF EXPERIMENTS:
LAB CYCLE-1
2. Introduction to python3
a) Printing your biodata on the screen
name = "Hemlata Reddy"
age = 30
address = "3-4-11/5 Chandra Nagar, Nizamabad"
email = "hemlatareddy62@[Link]"
phone = "9390295100"
print("Name:", name)
print("Age:", age)
print("Address:", address)
print("Email:", email)
print("Phone:", phone)

*****OUTPUT*****
Name: Hemlata Reddy
Age: 30
Address: 3-4-11/5 Chandra Nagar, Nizamabad
Email: hemlatareddy62@[Link]
Phone: 9390295100
b) Printing all primes less than a given number
num = int(input("Enter a number: "))
for i in range(2,num):
for j in range(2,num):
if i%j == 0:
break
if i == j:
print(i, end=' ')

*****OUTPUT*****
Enter a number: 11
2357

c) Finding all the factors of a number and show whether it is a perfect


number, i.e., the sum of all its factors(excluding the number itself) is
equal to the number itself
def factors(num):
factors_list = []
for i in range(1, num+1):
if num % i == 0:
factors_list.append(i)
return factors_list
def is_perfect(num):
factors_list = factors(num)
factors_list.pop()
sum_of_factors = sum(factors_list)
if sum_of_factors == num:
return True
else:
return False
num = 28
factors_list = factors(num)
print("Factors of", num, "are:", factors_list)
if is_perfect(num):
print(num, "is a perfect number.")
else:
print(num, "is not a perfect number.")

*****OUTPUT*****
Factors of 28 are: [1, 2, 4, 7, 14, 28]
28 is a perfect number.

3. Defining and using functions


a) Write a function to read data from a file and display it on the screen.

def read_and_display_file(filename):
with open(filename, 'r') as f:
file_contents = [Link]()
print(file_contents)
read_and_display_file('[Link]')

*****OUTPUT*****
Hi
Hello
welcome to kits college
b) Define a boolean function is palindrome(<input>)
def is_boolean_function_palindrome(boolean_function):
boolean_function = boolean_function.replace(" ", "")
if boolean_function == boolean_function[::-1]:
return True
else:
return False
boolean_function = "A and B or C or B and A"
if is_boolean_function_palindrome(boolean_function):
print("The boolean function is a palindrome!")
else:
print("The boolean function is not a palindrome.")

*****OUTPUT*****
The boolean function is not a palindrome.

c) Write a function collatz(x) which does the following: if x is odd, x =


3x + 1; if x is even,
then x = x/2. Return the number of steps it takes for x = 1
def collatz(x):
count = 0
while x != 1:
if x % 2 == 0:
x //= 2
else:
x=3*x+1
count += 1
return count
no_of_steps=collatz(6)
print("Number of steps it takes for x=1:",no_of_steps)

*****OUTPUT*****
Number of steps it takes for x=1: 8
d) Write a function(m,s)=exp(-(x-m)2/(2s)2)/sqrt(2pi)s that computes
he Normal Distribution.
import math

def N(m, s, x):


"""
Computes the normal distribution function N(m, s) for a given value of x.

Parameters:
m (float): mean value
s (float): standard deviation
x (float): input value for which to compute the normal distribution

Returns:
float: value of the normal distribution function for the given parameters
"""
exponent = -((x - m)*2) / (2 * s*2)
denominator = s * [Link](2 * [Link])
return [Link](exponent) / denominator
result = N(0, 1, 1.5)
print(result)
******OUTPUT*****
0.18844698973586405

4) The package numpy


a) Creating a matrix of given order m x n containing random numbers
in the range 1 to 99999
import random
m=5
n=4
matrix = [[0 for j in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
matrix[i][j] = [Link](1, 99999)
for row in matrix:
print(row)

*****OUTPUT*****
[77291, 2039, 20022, 31360]
[32580, 33403, 80205, 39522]
[7951, 9795, 71833, 15547]
[34533, 60502, 85012, 19425]
[91152, 68, 87463, 49556]

b) Write a program that adds, subtracts and multiplies two matrices.


Provide an interface such that, based on the prompt, the function
(addition, subtraction, multiplication) should be performed.
import numpy as np
def matrix_operation():
operation = input("What operation would you like to perform? (+, -, *): ")
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
matrix1 = [Link]((rows, cols))
matrix2 = [Link]((rows, cols))
print("Enter the elements of matrix 1:")
for i in range(rows):
for j in range(cols):
matrix1[i][j] = float(input())
print("Enter the elements of matrix 2:")
for i in range(rows):
for j in range(cols):
matrix2[i][j] = float(input())
if operation == "+":
result = matrix1 + matrix2
print("Result:")
print(result)
elif operation == "-":
result = matrix1 - matrix2
print("Result:")
print(result)
elif operation == "*":
result = [Link](matrix1, matrix2)
print("Result:")
print(result)
else:
print("Invalid operation")
matrix_operation()

*****OUTPUT*****
What operation would you like to perform? (+, -, *): +
Enter the number of rows: 2
Enter the number of columns: 2
Enter the elements of matrix 1:
4
4
4
5
Enter the elements of matrix 2:
6
7
8
9
Result:
[[10. 11.]
[12. 14.]]

c) Write a program to solve a system of n linear equations in n


variables using matrix
inverse
import numpy as np

def solve_system(A, b):


A_inv = [Link](A)
x = [Link](A_inv, b)
return x
A = [Link]([[1, 1, 1], [0, 2, 5], [2, 5, -1]])
b = [Link]([6, -4, 27])
x = solve_system(A, b)
print("Solution vector: ", x)

*****OUTPUT*****
Solution vector: [ 5. 3. -2.]

5. The package scipy and pyplot


a) Finding if two sets of data have the same mean value
import numpy as np

# Two sets of data


data1 = [Link](10, 2, 100)
data2 = [Link](10, 2, 100)

# Calculate mean values


mean1 = [Link](data1)
mean2 = [Link](data2)

# Compare mean values


if mean1 == mean2:
print('The means of the two datasets are equal')
else:
print('The means of the two datasets are different')
*****OUTPUT*****
The means of the two datasets are different

b) Plotting data read from a file


import [Link] as plt
x = []
y = []
with open('[Link]', 'r') as file:
for line in file:
parts = [Link]()
[Link](float(parts[0]))
[Link](float(parts[1]))
[Link](x, y)
[Link]('x-axis')
[Link]('y-axis')
[Link]('Data Plot')
[Link]()

*****OUTPUT*****
c) Fitting a function through a set a data points using polyfit function
import numpy as np
import [Link] as plt

x1 = [Link]([1, 2, 3, 4, 5])
y1 = [Link]([2, 3, 5, 6, 8])

x2 = [Link]([1, 2, 3, 4, 5])
y2 = [Link]([3, 5, 6, 7, 9])
coeffs1 = [Link](x1, y1, deg=2)

coeffs2 = [Link](x2, y2, deg=3)

y_fit1 = [Link](coeffs1, x1)


y_fit2 = [Link](coeffs2, x2)

[Link](x1, y1, label='Data set 1')


[Link](x1, y_fit1, label='Polynomial fit 1')

[Link](x2, y2, label='Data set 2')


[Link](x2, y_fit2, label='Polynomial fit 2')

[Link]()
[Link]()

print("Coefficients for first data set:", coeffs1)


print("Coefficients for second data set:", coeffs2)

*****OUTPUT*****
Coefficients for first data set: [0.07142857 1.07142857 0.8 ]
Coefficients for second data set: [ 0.16666667 -1.5 5.33333333 -1. ]

d) Plotting a histogram of a given data set

import [Link] as plt


data = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7]
[Link](data)
[Link]('Value')
[Link]('Frequency')
[Link]()

*****OUTPUT*****

6. The Strings Package


a) Read text from a file and print the number of lines, words and
characters
filename = input("Enter the file name: ")
with open(filename, 'r') as file:
data = [Link]()
num_lines = len([Link]('\n'))
num_words = len([Link]())
num_chars = len(data)
print("Number of lines:", num_lines)
print("Number of words:", num_words)
print("Number of characters:", num_chars)

*****OUTPUT*****
Enter the file name: [Link]
Number of lines: 4
Number of words: 8
Number of characters: 49

b) Read text from a file and return a list of all n letter words beginning
with a vowel
def get_n_letter_words_vowel(filename, n):
vowel_set = set(['a', 'e', 'i', 'o', 'u'])
words = []
with open(filename, 'r') as file:
for line in file:
for word in [Link]():
if len(word) == n and word[0].lower() in vowel_set:
[Link](word)
return words
words = get_n_letter_words_vowel('[Link]', 3)
print(words)
****OUTPUT*****
['are', 'ece']

c) Finding a secret message hidden in a paragraph of text


import re
paragraph = "This is a paragraph with a secret message hidden inside. The
message is: 'Hello World'."
pattern = r"'(.*?)'"
matches = [Link](pattern, paragraph)
print(matches[0])

*****OUTPUT*****
Hello World

d) Plot a histogram of words according to their length from text read


from a file

import [Link] as plt


with open('text_file.txt', 'r') as file:
text_data = [Link]()
words = text_data.split()
word_lengths = [len(word) for word in words]
[Link](word_lengths, bins=range(min(word_lengths), max(word_lengths)
+ 2, 1), edgecolor='black')
[Link]('Word length')
[Link]('Frequency')
[Link]('Histogram of word lengths')
[Link]()
*****OUTPUT*****

You might also like