Pytho Aman Sinha
Pytho Aman Sinha
To understand and demonstrate the use of basic data types in Python, such as integers, floats,
strings, booleans, and type conversion.
Required Setup:
Theory:
In Python, data types specify what kind of value an object holds. Common basic data types
include:
Program Code:
# Demonstrating Basic Data Types in Python
# 1. Integer (int)
a = 10
print("Value of a:", a)
print("Type of a:", type(a))
# 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))
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 d: True
Type of d: <class 'bool'>
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:
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:
Where:
import math
# Main program
def main():
# Calculating distance
print(f"\nThe distance between the points ({x1}, {y1}) and ({x2}, {y2}) is: {distance:.2f}")
if __name__ == "__main__":
main()
Explanation of Code:
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:
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:
Theory:
def calculate_harmonic_sum(n):
return harmonic_sum
# Main program
def main():
if n <= 0:
return
result = calculate_harmonic_sum(n)
print(f"\nThe decimal equivalent of the series 1 + 1/2 + 1/3 + ... + 1/{n} is: {result:.6f}")
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:
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:
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:
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
primes = find_n_primes(n)
print(f"The first {n} prime numbers are: {primes}")
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:
Objective:
Required Setup:
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)
# 2. Tuple
colors = ("red", "green", "blue", "yellow") # Creating a tuple
print("\nTuple of colors:", 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:
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:
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
Explanation of Code:
Output:
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:
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
Explanation of Code:
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:
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:
Required Setup:
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:
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.")
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)
print("\nMatrix B:")
for row in B:
print(row)
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:
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:
Required Setup:
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:
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.")
# 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)
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:
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:
Required Setup:
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())
# Main program
def main():
# Input from the user
user_input = input("Enter a string to check if it's a palindrome: ")
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:
Required Setup:
Theory:
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,
}
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
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.
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'
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:
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
# Main program
def main():
# Path to the file (make sure the file exists)
file_path = 'sample.txt'
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:
Required Setup:
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
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:
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.