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

Python Programming Experiments Guide

The document outlines a series of experiments demonstrating various programming concepts in Python, including checking for prime numbers, operations on data structures, functions and classes, string manipulation, mathematical operations, plotting graphs, statistical calculations, and data handling with libraries like NumPy and Pandas. Each experiment includes an aim, procedure, program code, sample output, and a result indicating successful execution. The experiments cover a wide range of topics, showcasing practical applications of Python in data science and programming.
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)
3 views11 pages

Python Programming Experiments Guide

The document outlines a series of experiments demonstrating various programming concepts in Python, including checking for prime numbers, operations on data structures, functions and classes, string manipulation, mathematical operations, plotting graphs, statistical calculations, and data handling with libraries like NumPy and Pandas. Each experiment includes an aim, procedure, program code, sample output, and a result indicating successful execution. The experiments cover a wide range of topics, showcasing practical applications of Python in data science and programming.
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:1

Prime Number
EXPERIMENT 1
Program using Conditional and Looping Constructs
Aim:
To check whether a given number is a prime number using conditional and looping constructs.
Procedure:
1. Read an integer from the user.
2. Check divisibility using a loop.
3. Display whether the number is prime or not.
Program:
num = int(input("Enter a number: "))
flag = 0

if num <= 1:
flag = 1
else:
for i in range(2, num):
if num % i == 0:
flag = 1
break

if flag == 0:
print("Prime Number")
else:
print("Not a Prime Number")
Sample Output:
Enter a number: 7
Prime Number
Result:
The program successfully identified whether the given number is prime.

EXPERIMENT 2
Program using List, Tuple, Set and Dictionary
Aim:
To demonstrate operations on list, tuple, set, and dictionary.
Procedure:
1. Create each data structure.
2. Perform basic insert and display operations.
Program:
my_list = [1, 2, 3]
my_list.append(4)
print("List:", my_list)

my_tuple = (10, 20, 30)


print("Tuple:", my_tuple)

my_set = {1, 2, 3}
my_set.add(4)
print("Set:", my_set)

my_dict = {"A": 1, "B": 2}


my_dict["C"] = 3
print("Dictionary:", my_dict)
Sample Output:
List: [1, 2, 3, 4]
Tuple: (10, 20, 30)
Set: {1, 2, 3, 4}
Dictionary: {'A': 1, 'B': 2, 'C': 3}
Result:
Operations on different Python data structures were executed successfully.
EXPERIMENT 3
Program using Functions and Classes
Aim:
To demonstrate the use of functions and classes in Python.
Procedure:
1. Define a function.
2. Define a class and method.
3. Execute both.
Program:
def square(n):
return n * n

class Demo:
def show(self):
print("Class Method Executed")

print("Square:", square(5))
obj = Demo()
[Link]()
Sample Output:
Square: 25
Class Method Executed
Result:
The function and class methods were executed successfully.

EXPERIMENT 4
Program using Strings and Files
Aim:
To perform basic string operations and demonstrate file handling operations in Python.
Procedure:
1. Read a string.
2. Perform string operations like uppercase conversion.
3. Create a file and write data into it.
4. Read the contents of the file and display it.
Program:
text = "Data Science"
print([Link]())

f = open("[Link]", "w")
[Link](text)
[Link]()

f = open("[Link]", "r")
print([Link]())
[Link]()
Sample Output:
DATA SCIENCE
Data Science
Result:
String manipulation and file operations were completed successfully.

EXPERIMENT 5
Data Creation and Mathematical Operations
Aim:
To create numerical data and perform basic mathematical operations in Python.
Procedure:
1. Initialize numerical variables.
2. Perform addition, subtraction, multiplication, and division.
3. Display the results.
Program:
a = 10
b=5
print(a+b)
print(a-b)
print(a*b)
print(a/b)
Sample Output:
15
5
50
2.0
Result:
Mathematical operations were executed successfully.

EXPERIMENT 6
Graphs and Plotting
Aim:
To plot a simple line graph using Python.
Procedure:
1. Import matplotlib library.
2. Define x and y values.
3. Plot the graph.
4. Display the graph.
Program:
import [Link] as plt
x = [1,2,3,4]
y = [10,20,30,40]
[Link](x,y)
[Link]()
Sample Output:
(Line graph window displayed)
Result:
Line graph plotted successfully.

EXPERIMENT 7
Statistical Description without Libraries
Aim:
To calculate statistical measures without using built-in libraries.
Procedure:
1. Store numerical values in a list.
2. Compute mean manually.
3. Find maximum and minimum values.
4. Display the results.
Program:
data = [10,20,30,40]
mean = sum(data)/len(data)
print("Mean:", mean)
print("Max:", max(data))
print("Min:", min(data))
Sample Output:
Mean: 25
Max: 40
Min: 10
Result:
Statistical measures were calculated successfully.

EXPERIMENT 8
Generation of Correlation Coefficient
Aim:
To generate the correlation coefficient between two datasets.
Procedure:
1. Create two numerical datasets.
2. Use NumPy to calculate correlation coefficient.
3. Display the result.
Program:
import numpy as np
x = [Link]([1,2,3,4])
y = [Link]([2,4,6,8])
print([Link](x,y))
Sample Output:
[[1. 1.]
[1. 1.]]
Result:
Correlation coefficient generated successfully.

EXPERIMENT 9
Linear Regression Model
Aim:
To implement a simple linear regression model.
Procedure:
1. Import required libraries.
2. Create independent and dependent variables.
3. Train the linear regression model.
4. Predict output values.
Program:
from sklearn.linear_model import LinearRegression
import numpy as np
X = [Link]([[1],[2],[3],[4]])
y = [Link]([2,4,6,8])
model = LinearRegression()
[Link](X,y)
print([Link]([[5]]))
Sample Output:
[10.]
Result:
Linear regression model executed successfully.

EXPERIMENT 10
Creation of 1D, 2D and 3D NumPy Arrays
Aim:
To create one-dimensional, two-dimensional, and three-dimensional NumPy arrays.
Procedure:
1. Import NumPy library.
2. Create arrays of different dimensions.
3. Display the arrays.
Program:
import numpy as np
print([Link]([1,2,3]))
print([Link]([[1,2],[3,4]]))
print([Link]([[[1,2],[3,4]]]))
Sample Output:
[1 2 3]
[[1 2]
[3 4]]
[[[1 2]
[3 4]]]
Result:
NumPy arrays were created successfully.

EXPERIMENT 11
Array Slicing and Indexing
Aim:
To perform slicing and indexing operations on NumPy arrays.
Procedure:
1. Create a NumPy array.
2. Apply slicing using index ranges.
3. Display the sliced array.
Program:
import numpy as np
arr = [Link]([10,20,30,40,50])
print(arr[1:4])
Sample Output:
[20 30 40]
Result:
Array slicing and indexing performed successfully.

EXPERIMENT 12
Reindexing and Aligning DataFrames
Aim:
To perform reindexing and alignment operations on Pandas DataFrames.
Procedure:
1. Create a DataFrame.
2. Apply reindexing with new labels.
3. Observe alignment and missing values.
Program:
import pandas as pd
df = [Link]({"A":[1,2],"B":[3,4]}, index=['x','y'])
print([Link](['y','x','z']))
Sample Output:
AB
y 2.0 4.0
x 1.0 3.0
z NaN NaN
Result:
Reindexing and alignment completed successfully.
EXPERIMENT 13
Line, Bar, Histogram and Box Plot
Aim:
To generate different types of plots using matplotlib.
Procedure:
1. Import matplotlib library.
2. Provide dataset.
3. Generate histogram and other plots.
4. Display the plots.
Program:
import [Link] as plt
data = [10,20,30,40]
[Link](data)
[Link]()
Sample Output:
(Histogram displayed)
Result:
Different plots were displayed successfully.

EXPERIMENT 14
Seaborn Plots and Customization
Aim:
To create plots using Seaborn library with basic customization.
Procedure:
1. Import seaborn and matplotlib libraries.
2. Provide dataset.
3. Generate seaborn plot.
4. Display the plot.
Program:
import seaborn as sns
import [Link] as plt
[Link](data=[10,20,30,40])
[Link]()
Sample Output:
(Seaborn box plot displayed)
Result:
Seaborn plot was generated successfully.

Common questions

Powered by AI

Experiment 6 involves importing the `matplotlib.pyplot` library, defining x and y values, and using `plt.plot()` to create a line graph which is then displayed using `plt.show()`. The outcome is a successfully plotted line graph showing a relationship between the x and y data points provided .

Array slicing in Experiment 11 involves accessing a subset of elements from a NumPy array using index ranges. The expression `arr[1:4]` retrieves elements from index 1 to 3, resulting in a sliced array `[20, 30, 40]`. This operation showcases NumPy's ability to efficiently manipulate and access subarrays .

Experiment 12 demonstrates reindexing by changing the DataFrame index order using `reindex()`. Missing labels result in NaNs for missing values. This process highlights challenges such as handling missing data and ensuring consistent data alignment. It underscores the importance of understanding index operations for effective DataFrame manipulation .

Experiment 3 defines a function `square` to compute the square of a number and a class `Demo` with a method `show` that prints a message. It illustrates the use of functions for discrete tasks and classes for encapsulating behavior and data under a unified structure. A `Demo` object is created to execute the class method alongside the function, demonstrating Python's modular structure allowing structured programming .

In Experiment 8, NumPy is used to calculate the correlation coefficient using `np.corrcoef()`, which computes the degree to which two datasets vary together. The output matrix shows a perfect positive linear relationship (value of 1) between the two datasets, indicating that as one increases, the other does too in a linear fashion .

The program checks if a number is prime by testing divisibility from 2 to one less than the number. If no divisors are found, it prints "Prime Number". If the input is 1, it prints "Not a Prime Number" since numbers less than or equal to 1 are not prime .

Seaborn is beneficial for creating aesthetically pleasing and informative statistical plots with minimal effort, allowing comprehensive customization and easy integration with Matplotlib. However, its abstraction layer can be limiting for highly complex and custom plot requirements, and users must be familiar with both Seaborn and Matplotlib for full customization potential. Experiment 14 shows these benefits visually .

Experiment 2 demonstrates operations like adding elements to a list and set, displaying tuple contents, and updating a dictionary. Lists are mutable and ordered, tuples are immutable and ordered, sets are mutable and unordered with no duplicates, and dictionaries store key-value pairs, allowing for fast retrieval by key. Each structure serves specific use cases depending on requirements such as mutability, ordering, and data retrieval .

In Experiment 9, a linear regression model is created using the `LinearRegression` class from the `sklearn.linear_model` library. Independent and dependent variables are initialized, the model is trained using the `fit` method, and predictions are made using `predict`. The predicted output corresponds linearly with the input data based on the trained model, demonstrating how data-driven predictions can be made .

The mean is calculated manually by summing all elements in the list and then dividing by the count of elements. This straightforward calculation is performed using basic arithmetic operations without relying on external libraries .

You might also like