0% found this document useful (0 votes)
51 views27 pages

Pytho Aman Sinha

python

Uploaded by

kypgpsiwan
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)
51 views27 pages

Pytho Aman Sinha

python

Uploaded by

kypgpsiwan
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
You are on page 1/ 27

Practical: 1

Practical: Demonstrating Basic Data Types


in Python
Objective:

To understand and demonstrate the use of basic data types in Python, such as integers, floats,
strings, booleans, and type conversion.

Required Setup:

Python environment (Python 3.x).

Theory:

In Python, data types specify what kind of value an object holds. Common basic data types
include:

 int: Represents integer values.


 float: Represents floating-point numbers.
 str: Represents text data or sequences of characters.
 bool: Represents Boolean values, either True or False.
 type() function: Can be used to check the type of a variable.

Program Code:
# Demonstrating Basic Data Types in Python

# 1. Integer (int)
a = 10
print("Value of a:", a)
print("Type of a:", type(a))

# 2. Floating point number (float)


b = 3.14
print("\nValue of b:", b)
print("Type of b:", type(b))

# 3. String (str)
c = "Hello, Python!"
print("\nValue of c:", c)
print("Type of c:", type(c))

# 4. Boolean (bool)
d = True
print("\nValue of d:", d)
print("Type of d:", type(d))

# 5. Type conversion (casting)


# Convert integer to float
a_to_float = float(a)
print("\nConverting a (int) to float:", a_to_float)

# Convert float to int


b_to_int = int(b)
print("Converting b (float) to int:", b_to_int)

# Convert string to integer (if valid numeric string)


e = "123"
e_to_int = int(e)
print("\nConverting e (string) to int:", e_to_int)

# 6. Checking data type after conversion


print("\nType of a_to_float:", type(a_to_float))
print("Type of b_to_int:", type(b_to_int))
print("Type of e_to_int:", type(e_to_int))

Explanation of Code:

1. Integer (int): The variable a is assigned an integer value, and its type is printed using
the type() function.
2. Floating point (float): The variable b holds a floating-point value.
3. String (str): The variable c holds a string.
4. Boolean (bool): The variable d stores a boolean value (True or False).
5. Type Conversion: Demonstrates conversion between different types:
o Integer to float.
o Float to integer.
o String to integer (if the string contains numeric characters).
6. Type Check: The type() function is used after conversion to check the new data
types of the variables.

Output:
Value of a: 10
Type of a: <class 'int'>

Value of b: 3.14
Type of b: <class 'float'>

Value of c: Hello, Python!


Type of c: <class 'str'>

Value of d: True
Type of d: <class 'bool'>

Converting a (int) to float: 10.0


Converting b (float) to int: 3

Converting e (string) to int: 123

Type of a_to_float: <class 'float'>


Type of b_to_int: <class 'int'>
Type of e_to_int: <class 'int'>

Conclusion:
This program demonstrates how to work with various basic data types in Python, such as
integers, floats, strings, and booleans, along with performing type conversions and checking
data types.
Practical: 2
Practical: Computing the Distance Between
Two Points Using the Pythagorean Theorem
Objective:

To create a Python program that computes the distance between two points in a 2D plane
using the Pythagorean theorem. The program will take input from the user for the coordinates
of the two points.

Required Setup:

Python environment (Python 3.x).

Theory:

The distance ddd between two points (x1,y1)(x_1, y_1)(x1,y1) and (x2,y2)(x_2, y_2)(x2,y2)
in a 2D space can be calculated using the Pythagorean theorem:

d=(x2−x1)2+(y2−y1)2d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}d=(x2−x1)2+(y2−y1)2

Where:

 (x1,y1)(x_1, y_1)(x1,y1) are the coordinates of the first point.


 (x2,y2)(x_2, y_2)(x2,y2) are the coordinates of the second point.

import math

# Function to calculate distance between two points

def calculate_distance(x1, y1, x2, y2):

return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

# Main program

def main():

# Taking input from the user for the first point

x1 = float(input("Enter the x-coordinate of the first point: "))

y1 = float(input("Enter the y-coordinate of the first point: "))


# Taking input from the user for the second point

x2 = float(input("Enter the x-coordinate of the second point: "))

y2 = float(input("Enter the y-coordinate of the second point: "))

# Calculating distance

distance = calculate_distance(x1, y1, x2, y2)

# Displaying the result

print(f"\nThe distance between the points ({x1}, {y1}) and ({x2}, {y2}) is: {distance:.2f}")

# Run the main program

if __name__ == "__main__":

main()

Explanation of Code:

1. Importing the math module: This module provides access to mathematical


functions, including sqrt() for calculating square roots.
2. Function Definition:
o calculate_distance(x1, y1, x2, y2): This function implements the
formula for distance and returns the calculated value.
3. Main Program:
o Takes user input for the coordinates of the two points.
o Converts the inputs to float to allow for decimal values.
o Calls the calculate_distance function to compute the distance.
o Outputs the distance formatted to two decimal places.

Output:

When you run the program, it will prompt the user to enter the coordinates of the two points.
Here’s an example of what the output may look like:

Enter the x-coordinate of the first point: 2


Enter the y-coordinate of the first point: 3
Enter the x-coordinate of the second point: 5
Enter the y-coordinate of the second point: 7

The distance between the points (2.0, 3.0) and (5.0, 7.0) is: 5.00

Conclusion:

This program effectively calculates the distance between two points in a 2D plane using the
Pythagorean theorem. Understanding how to work with user input, functions, and
mathematical operations in Python is crucial for various applications in programming and
data analysis.

Practical: 3
Practical: Calculating the Sum of the Series
1+12+13+…+1n1 + \frac{1}{2} + \frac{1}{3}
+ \ldots + \frac{1}{n}1+21+31+…+n1
Objective:

To write a Python program that calculates and prints the decimal equivalent of the series
1+12+13+…+1n1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}1+21+31+…+n1 using
a for loop.

Required Setup:

Python environment (Python 3.x).

Theory:

The series 1+12+13+…+1n1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}1+21+31+…


+n1 is known as the Harmonic Series. The program will:

1. Take an integer input nnn from the user.


2. Use a for loop to iterate from 1 to nnn.
3. Sum the decimal values of the series.
4. Print the total sum.

# Function to calculate the sum of the series

def calculate_harmonic_sum(n):

harmonic_sum = 0.0 # Initialize sum as a float

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

harmonic_sum += 1 / i # Add the decimal equivalent of 1/i to the sum

return harmonic_sum

# Main program

def main():

# Taking input from the user


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

if n <= 0:

print("Please enter a positive integer greater than 0.")

return

# Calculating the harmonic sum

result = calculate_harmonic_sum(n)

# Displaying the result

print(f"\nThe decimal equivalent of the series 1 + 1/2 + 1/3 + ... + 1/{n} is: {result:.6f}")

# Run the main program

if __name__ == "__main__":

main()

Explanation of Code:

1. Function Definition:
o calculate_harmonic_sum(n): This function calculates the harmonic sum
using a for loop. It initializes harmonic_sum to 0.0 and adds the value of 1i\
frac{1}{i}i1 for each iii from 1 to nnn.
2. Main Program:
o It prompts the user for input and ensures that the input is a positive integer.
o Calls the calculate_harmonic_sum function to compute the sum.
o Displays the result formatted to six decimal places.

Output:

When you run the program, it will prompt the user to enter a positive integer nnn. Here’s an
example of what the output may look like:

Enter a positive integer n: 5

The decimal equivalent of the series 1 + 1/2 + 1/3 + ... + 1/5 is: 2.283334

Conclusion:

This program effectively demonstrates how to use a for loop in Python to compute the sum
of a mathematical series. Understanding loops and arithmetic operations is essential for
solving various programming problems.
Practical: 4
Practical: Finding the First n Prime
Numbers and Demonstrating List and
Tuple in Python
Part 1: Finding the First n Prime Numbers

Objective:

To write a Python program that finds and prints the first nnn prime numbers.

Required Setup:

Python environment (Python 3.x).

Theory:

A prime number is a natural number greater than 1 that cannot be formed by multiplying two
smaller natural numbers. The first few prime numbers are 2, 3, 5, 7, 11, etc. The program
will:

1. Take an integer input nnn from the user.


2. Check each number for primality until nnn prime numbers are found.
3. Print the list of prime numbers.

Program Code:
# Function to check if a number is prime
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# Function to find the first n prime numbers


def find_n_primes(n):
primes = [] # Initialize an empty list to store prime numbers
num = 2 # Starting from the first prime number
while len(primes) < n:
if is_prime(num):
primes.append(num) # Add the prime number to the list
num += 1
return primes
# Main program
def main():
n = int(input("Enter the number of prime numbers to find: "))
if n <= 0:
print("Please enter a positive integer greater than 0.")
return

primes = find_n_primes(n)
print(f"The first {n} prime numbers are: {primes}")

# Run the main program


if __name__ == "__main__":
main()

Explanation of Code:

1. Function Definition:
o is_prime(num): Checks if a number is prime by testing divisibility from 2 up to the
square root of the number.
find_n_primes(n): Uses a loop to find the first nnn prime numbers, storing them
o
in a list.
2. Main Program:
o Prompts the user for input and ensures it is a positive integer.
o Calls the find_n_primes function to compute the prime numbers.
o Outputs the list of prime numbers.

Output:

When you run the program, it will prompt the user to enter the number of prime numbers to
find. Here’s an example output:

Enter the number of prime numbers to find: 5


The first 5 prime numbers are: [2, 3, 5, 7, 11]

Part 2: Demonstrating List and Tuple in Python

Objective:

To demonstrate the differences and usage of lists and tuples in Python.

Required Setup:

Python environment (Python 3.x).

Theory:

 List: A mutable, ordered collection of items that can contain duplicate elements. Defined
using square brackets [].
 Tuple: An immutable, ordered collection of items that can also contain duplicates. Defined
using parentheses ().
Program Code:
# Demonstrating List and Tuple in Python

# 1. List
fruits = ["apple", "banana", "cherry", "date"] # Creating a list
print("List of fruits:", fruits)

# Adding an item to the list


fruits.append("elderberry")
print("List after adding elderberry:", fruits)

# Removing an item from the list


fruits.remove("banana")
print("List after removing banana:", fruits)

# Accessing items in the list


print("First fruit in the list:", fruits[0])

# 2. Tuple
colors = ("red", "green", "blue", "yellow") # Creating a tuple
print("\nTuple of colors:", colors)

# Accessing items in the tuple


print("First color in the tuple:", colors[0])

# Trying to change an item in the tuple (will cause an error)


try:
colors[1] = "purple" # This will raise a TypeError
except TypeError as e:
print("Error:", e)

# Displaying the length of the list and tuple


print("\nLength of the fruits list:", len(fruits))
print("Length of the colors tuple:", len(colors))

Explanation of Code:

1. List Demonstration:
o A list of fruits is created and printed.
o Items are added and removed from the list using append() and remove().
o Accessing items using indexing.
2. Tuple Demonstration:
o A tuple of colors is created and printed.
o Items are accessed using indexing.
o Attempting to modify a tuple raises a TypeError, demonstrating its immutability.
3. Length Calculation: The lengths of both the list and tuple are displayed using len().

Output:

When you run this part of the program, you will see the following output:

List of fruits: ['apple', 'banana', 'cherry', 'date']


List after adding elderberry: ['apple', 'banana', 'cherry', 'date',
'elderberry']
List after removing banana: ['apple', 'cherry', 'date', 'elderberry']
First fruit in the list: apple

Tuple of colors: ('red', 'green', 'blue', 'yellow')


First color in the tuple: red
Error: 'tuple' object does not support item assignment

Length of the fruits list: 4


Length of the colors tuple: 4

Conclusion:

This practical demonstrates how to find the first nnn prime numbers and illustrates the
differences between lists and tuples in Python. Understanding these concepts is fundamental
for effective data manipulation and storage in programming.
Practical: 5
Practical: Looping Over a Sequence and
Countdown Using Loops in Python
Part 1: Looping Over a Sequence Using a For Loop

Objective:

To write a Python program that uses a for loop to iterate over a sequence (like a list or a
string) and print each element.

Required Setup:

Python environment (Python 3.x).

Theory:

A for loop in Python allows you to iterate over a sequence, such as a list, tuple, or string,
executing a block of code for each item in the sequence.

Program Code:
# Program to loop over a sequence using a for loop

# Sample sequence (list of fruits)


fruits = ["apple", "banana", "cherry", "date"]

# Using for loop to iterate over the list


print("List of fruits:")
for fruit in fruits:
print(fruit)

Explanation of Code:

1. A list of fruits is created.


2. A for loop is used to iterate over each element in the fruits list.
3. Each fruit is printed to the console.

Output:

When you run the program, the output will be:

List of fruits:
apple
banana
cherry
date
Part 2: Countdown from a User-Provided Number Using a While Loop

Objective:

To write a Python program that uses a while loop to ask the user for a number and prints a
countdown from that number to zero.

Required Setup:

Python environment (Python 3.x).

Theory:

A while loop repeatedly executes a block of code as long as a specified condition is true.
This program will continue to print the countdown until it reaches zero.

Program Code:
# Program to print a countdown using a while loop

# Asking the user for a number


number = int(input("Enter a number to start the countdown: "))

# Countdown using a while loop


print("\nCountdown:")
while number >= 0:
print(number)
number -= 1 # Decrease the number by 1

Explanation of Code:

1. The user is prompted to enter a number, which is converted to an integer.


2. A while loop is used to check if the number is greater than or equal to zero.
3. Inside the loop, the current number is printed, and then the number is decremented by 1.

Output:

When you run the program, the output will depend on the number the user inputs. For
example, if the user enters 5, the output will be:

Enter a number to start the countdown: 5

Countdown:
5
4
3
2
1
0
Conclusion:

This practical illustrates the use of for and while loops in Python. The for loop is useful for
iterating over sequences, while the while loop is effective for executing code based on a
condition, such as counting down from a number.
Practical: 6
Practical: Adding and Multiplying Matrices
in Python
Part 1: Adding Matrices

Objective:

To write a Python program that adds two matrices.

Required Setup:

Python environment (Python 3.x).

Theory:

Matrix addition involves adding corresponding elements of two matrices of the same
dimensions. If matrix AAA and matrix BBB are both of size m×nm \times nm×n, their sum
CCC is defined as:

C[i][j]=A[i][j]+B[i][j]C[i][j] = A[i][j] + B[i][j]C[i][j]=A[i][j]+B[i][j]

Program Code:
# Function to add two matrices
def add_matrices(A, B):
# Check if the dimensions are the same
if len(A) != len(B) or len(A[0]) != len(B[0]):
raise ValueError("Matrices must have the same dimensions for
addition.")

# Create a result matrix with the same dimensions initialized to 0


result = [[0 for _ in range(len(A[0]))] for _ in range(len(A))]

# Adding corresponding elements


for i in range(len(A)):
for j in range(len(A[0])):
result[i][j] = A[i][j] + B[i][j]

return result

# Main program
def main():
# Define two matrices
A = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
B = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]

# Adding matrices
result = add_matrices(A, B)

# Displaying the result


print("Matrix A:")
for row in A:
print(row)

print("\nMatrix B:")
for row in B:
print(row)

print("\nSum of A and B:")


for row in result:
print(row)

# Run the main program


if __name__ == "__main__":
main()

Explanation of Code:

1. Function Definition:
o add_matrices(A, B): This function takes two matrices as input and checks if
their dimensions match. It initializes a result matrix and computes the sum by
iterating through each element.
2. Main Program:
o Two sample matrices AAA and BBB are defined.
o The add_matrices function is called, and the result is printed.

Output:

When you run the program, the output will be:

Matrix A:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Matrix B:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]

Sum of A and B:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Part 2: Multiplying Matrices

Objective:

To write a Python program that multiplies two matrices.

Required Setup:

Python environment (Python 3.x).

Theory:

Matrix multiplication is defined such that if matrix AAA is of size m×nm \times nm×n and
matrix BBB is of size n×pn \times pn×p, the resulting matrix CCC will be of size m×pm \
times pm×p. Each element is calculated as:

C[i][j]=∑k=0n−1A[i][k]×B[k][j]C[i][j] = \sum_{k=0}^{n-1} A[i][k] \times B[k][j]C[i][j]=k=0∑n−1A[i]


[k]×B[k][j]

Program Code:
# Function to multiply two matrices
def multiply_matrices(A, B):
# Check if multiplication is possible (columns of A must equal rows of
B)
if len(A[0]) != len(B):
raise ValueError("Number of columns in A must be equal to the
number of rows in B.")

# Create a result matrix with dimensions m x p


result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]

# Multiplying matrices
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]

return result

# Main program
def main():
# Define two matrices
A = [
[1, 2],
[3, 4]
]

B = [
[5, 6],
[7, 8]
]

# Multiplying matrices
result = multiply_matrices(A, B)
# Displaying the result
print("Matrix A:")
for row in A:
print(row)

print("\nMatrix B:")
for row in B:
print(row)

print("\nProduct of A and B:")


for row in result:
print(row)

# Run the main program


if __name__ == "__main__":
main()

Explanation of Code:

1. Function Definition:
o multiply_matrices(A, B): This function checks if the matrices can be
multiplied based on their dimensions. It initializes a result matrix and calculates the
product by iterating through the elements using three nested loops.
2. Main Program:
o Two sample matrices AAA and BBB are defined.
o The multiply_matrices function is called, and the result is printed.

Output:

When you run the program, the output will be:

Matrix A:
[1, 2]
[3, 4]

Matrix B:
[5, 6]
[7, 8]

Product of A and B:
[19, 22]
[43, 50]

Conclusion:

This practical demonstrates how to add and multiply matrices in Python. Matrix operations
are fundamental in various fields such as mathematics, physics, computer science, and
engineering.
Practical: 7
Practical: Checking if a String is a
Palindrome in Python
Objective:

To write a Python program that checks whether a given string is a palindrome.

Required Setup:

Python environment (Python 3.x).

Theory:

A palindrome is a string that reads the same forward and backward, ignoring spaces,
punctuation, and capitalization. For example, "racecar", "A man, a plan, a canal, Panama!",
and "No 'x' in Nixon" are all palindromes.

Program Code:
# Function to check if a string is a palindrome
def is_palindrome(s):
# Normalize the string: remove spaces, convert to lowercase
normalized_string = ''.join(char.lower() for char in s if
char.isalnum())

# Check if the normalized string is the same as its reverse


return normalized_string == normalized_string[::-1]

# Main program
def main():
# Input from the user
user_input = input("Enter a string to check if it's a palindrome: ")

# Check for palindrome


if is_palindrome(user_input):
print(f'"{user_input}" is a palindrome.')
else:
print(f'"{user_input}" is not a palindrome.')

# Run the main program


if __name__ == "__main__":
main()
Explanation of Code:

1. Function Definition:
o is_palindrome(s): This function takes a string as input and normalizes it by
removing non-alphanumeric characters and converting it to lowercase. It then
checks if the normalized string is equal to its reverse.
2. Main Program:
o Prompts the user for input.
o Calls the is_palindrome function and prints whether the string is a palindrome.

Output:

When you run the program, it will prompt the user to enter a string. Here are some example
outputs:

Example 1:
Enter a string to check if it's a palindrome: A man, a plan, a canal,
Panama!
"A man, a plan, a canal, Panama!" is a palindrome.

Example 2:
Enter a string to check if it's a palindrome: Hello, World!
"Hello, World!" is not a palindrome.
Conclusion:

This practical demonstrates how to check if a string is a palindrome in Python. Understanding


string manipulation and normalization is essential for solving various problems involving text
processing.
Practical: 8
Practical: Extracting Unique Values from a
Dictionary in Python
Objective:

To write a Python program that extracts unique values from a dictionary.

Required Setup:

Python environment (Python 3.x).

Theory:

In Python, a dictionary is a collection of key-value pairs. It is possible for multiple keys to


have the same value. This program will iterate through the values of the dictionary, collect
unique values, and return them.

Program Code:
# Function to extract unique values from a dictionary
def extract_unique_values(input_dict):
# Using a set to store unique values
unique_values = set(input_dict.values())
return unique_values

# Main program
def main():
# Sample dictionary with some duplicate values
sample_dict = {
'a': 1,
'b': 2,
'c': 3,
'd': 2,
'e': 1,
'f': 4,
}

# Extract unique values


unique_values = extract_unique_values(sample_dict)

# Displaying the results


print("Original Dictionary:")
print(sample_dict)
print("\nUnique Values:")
print(unique_values)

# Run the main program


if __name__ == "__main__":
main()
Explanation of Code:

1. Function Definition:
o extract_unique_values(input_dict): This function takes a dictionary as
input and uses a set to store unique values since sets inherently do not allow
duplicate entries.

2. Main Program:
o A sample dictionary is defined with some duplicate values.
o The extract_unique_values function is called to get the unique values.
o Both the original dictionary and the unique values are printed.

Output:

When you run the program, it will display the original dictionary and its unique values.
Here’s an example output:

Original Dictionary:
{'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 1, 'f': 4}

Unique Values:
{1, 2, 3, 4}
Conclusion:

This practical demonstrates how to extract unique values from a dictionary in Python. Using
a set is an efficient way to filter out duplicates.
Practical: 9

Practical: Reading a File Word by Word


and Counting Characters and Words in
Python
Objective:

To write Python programs that read a file word by word and count the number of characters
and words in the file.

Required Setup:

Python environment (Python 3.x) and a text file (e.g., sample.txt) for testing.

Part 1: Reading a File Word by Word

Theory:

To read a file word by word, we can use Python’s built-in file handling capabilities. The
read() and split() methods can be utilized to read the contents and split them into words.

Program Code:
# Function to read a file and print its contents word by word
def read_file_word_by_word(file_path):
try:
with open(file_path, 'r') as file:
print("Reading file word by word:")
for line in file:
words = line.split()
for word in words:
print(word)
except FileNotFoundError:
print("The file was not found.")

# Main program
def main():
# Path to the file (make sure the file exists)
file_path = 'sample.txt'

# Read the file word by word


read_file_word_by_word(file_path)

# Run the main program


if __name__ == "__main__":
main()

Explanation of Code:

1. Function Definition:
o read_file_word_by_word(file_path): This function opens a file, reads it line
by line, and splits each line into words. It prints each word individually.

2. Main Program:
o The file path is defined, and the function is called to read and display the file
contents.

Output:

Assuming sample.txt contains the text "Hello world! Welcome to Python programming.",
the output will be:

Reading file word by word:


Hello
world!
Welcome
to
Python
programming.

Part 2: Counting the Number of Characters and Words

Theory:

To count the number of characters and words in a file, we can utilize the same file reading
method, keeping track of the counts while reading.

Program Code:
# Function to count characters and words in a file
def count_characters_and_words(file_path):
try:
with open(file_path, 'r') as file:
content = file.read() # Read the entire file content
word_count = len(content.split()) # Count words
char_count = len(content) # Count characters

print(f"Number of words: {word_count}")


print(f"Number of characters: {char_count}")
except FileNotFoundError:
print("The file was not found.")

# Main program
def main():
# Path to the file (make sure the file exists)
file_path = 'sample.txt'

# Count characters and words in the file


count_characters_and_words(file_path)
# Run the main program
if __name__ == "__main__":
main()

Explanation of Code:

1. Function Definition:
o count_characters_and_words(file_path): This function reads the entire
content of the file at once. It counts the number of words by splitting the content
and counts characters using the len() function.

2. Main Program:
o Similar to the previous part, the file path is defined, and the function is called to
perform the counting.

Output:

Assuming sample.txt contains the same text, the output will be:

Number of words: 6
Number of characters: 42

Conclusion:

These practical examples demonstrate how to read a file word by word and count the number
of characters and words in Python. File handling is an essential skill for data processing and
text analysis tasks.
Practical: 10
Practical: Implementing Linear Search in
Python
Objective:

To write a Python program that performs a linear search on a list of elements.

Required Setup:

Python environment (Python 3.x).

Theory:

Linear search is a simple search algorithm that checks each element in a list sequentially until
it finds the target value or reaches the end of the list. It is effective for small datasets but can
be inefficient for large ones, with a time complexity of O(n)O(n)O(n), where nnn is the
number of elements in the list.

Program Code:
# Function to perform linear search
def linear_search(arr, target):
for index in range(len(arr)):
if arr[index] == target:
return index # Return the index of the target if found
return -1 # Return -1 if the target is not found

# Main program
def main():
# Sample list and target element
sample_list = [5, 3, 8, 4, 2, 7, 1]
target_value = 4

# Performing linear search


result_index = linear_search(sample_list, target_value)

# Displaying the results


if result_index != -1:
print(f"Element {target_value} found at index: {result_index}")
else:
print(f"Element {target_value} not found in the list.")

# Run the main program


if __name__ == "__main__":
main()
Explanation of Code:

1. Function Definition:
o linear_search(arr, target): This function iterates over each element in the
list arr. If the target element is found, it returns the index of that element. If the
loop completes without finding the target, it returns -1.

2. Main Program:
o A sample list and a target value are defined.
o The linear_search function is called, and the result is printed based on whether
the element was found.

Output:

When you run the program, it will display the index of the target element if found. Here’s an
example output for the given sample list and target value:

Element 4 found at index: 3

If you change the target_value to a number not in the list (e.g., 6), the output will be:

mathematica
Copy code
Element 6 not found in the list.

Conclusion:

This practical demonstrates how to implement and use a linear search algorithm in Python.
Understanding search algorithms is essential for efficiently finding data in collections.

You might also like