Python Programming Lab Manual
Python Programming Lab Manual
Certainly! To find the largest element among three numbers in Python, you
can use the built-in max() function, which simplifies the task. Here's a
straightforward example of how you can do this:
Explanation:
Example Usage:
ure! To display all prime numbers within a given interval in Python, you
can follow these steps:
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i=5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
if is_prime(num):
display_primes(start, end)
Explanation:
1. is_prime(n) Function:
o Checks if a number n is prime.
o Handles special cases (e.g., numbers less than or equal to 1, and
multiples of 2 and 3).
o Uses trial division up to the square root of n, with
optimizations for efficiency.
2. display_primes(start, end) Function:
o Iterates through the range from start to end.
o Uses the is_prime function to check if each number is prime
and prints it.
3. User Input:
o The program prompts the user to input the start and end of the
interval.
o Calls display_primes with the user-provided interval.
Example Usage:
11 13 17 19 23 29
This program effectively lists all prime numbers within the specified range.
Feel free to adjust it as needed!
ertainly! You can swap two numbers without using a temporary variable
by utilizing arithmetic operations or tuple unpacking. Below are two
methods to achieve this in Python:
a=a+b
b=a-b
a=a-b
return a, b
Here's a Python program that swaps two numbers using tuple unpacking:
return a, b
Explanation:
I) Arithmetic Operators
# Arithmetic Operators
a = 10
b=5
# Addition
add = a + b
# Subtraction
sub = a - b
# Multiplication
mul = a * b
# Division
div = a / b
floordiv = a // b
# Modulus
mod = a % b
# Exponentiation
exp = a ** b
# Arithmetic Operators
a = 10
b=5
# Addition
add = a + b
# Subtraction
sub = a - b
mul = a * b
# Division
div = a / b
# Floor Division
floordiv = a // b
# Modulus
mod = a % b
# Exponentiation
exp = a ** b
# Relational Operators
x = 15
y = 10
# Equal to
# Not equal to
# Greater than
# Less than
# Assignment Operators
a = 10
b=5
# Basic assignment
a=b
a += b
a -= b
a *= b
a /= b
a %= b
a **= b
a //= b
# Logical Operators
x = True
y = False
# AND operator
# OR operator
# NOT operator
V) Bitwise Operators
Bitwise operators are used to perform operations on binary representations
of integers.
# Bitwise Operators
a = 12 # 1100 in binary
b = 7 # 0111 in binary
# AND operator
bitwise_and = a & b
# OR operator
bitwise_or = a | b
# XOR operator
bitwise_xor = a ^ b
# Complement operator
bitwise_not = ~a
left_shift = a << 2
right_shift = a >> 2
Summary
Feel free to run these code snippets to see the operators in action!
Explanation:
Example Usage:
Enter the first complex number (in the form a+bj): 2+3j
Enter the second complex number (in the form a+bj): 1+4j
Python
# Function to print the multiplication table of a given number
def print_multiplication_table(number, up_to=10):
print(f"Multiplication table for {number}:")
for i in range(1, up_to + 1):
result = number * i
print(f"{number} x {i} = {result}")
# Optionally, you can change the range (up_to) to print more or fewer lines
print_multiplication_table(num)
Explanation:
1. Function Definition:
o print_multiplication_table(number, up_to=10): This function
prints the multiplication table for the given number up to
up_to times (default is 10). You can modify up_to to change the
range of the multiplication table if needed.
2. Input Number:
o The user is prompted to input a number for which the
multiplication table will be generated.
3. Loop:
o The for loop iterates from 1 to up_to, calculating the product of
the given number and the loop index (i), and prints the result in
a formatted manner.
4. Output:
o The multiplication table is printed line by line in the format
number x i = result.
Example Usage:
This program will print the multiplication table of any number entered by
the user, and you can adjust the range if you need a longer or shorter table.
Example Program
Let's create a function that takes two numbers as input and returns both
their sum and their product.
Parameters:
a (int or float): The first number
b (int or float): The second number
Returns:
tuple: A tuple containing the sum and the product of the two numbers
"""
# Calculate sum and product
sum_result = a + b
product_result = a * b
# Example usage
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
Explanation:
1. Function Definition:
o calculate_sum_and_product(a, b): This function takes two
parameters a and b. It calculates their sum and product, then
returns both results as a tuple (sum_result, product_result).
2. Return Multiple Values:
o By returning the values separated by commas, Python
automatically packs these values into a tuple. When the
function is called, the caller can unpack this tuple into
individual variables.
3. Example Usage:
o The user is prompted to input two numbers. The function is
called with these numbers, and the results (sum and product)
are unpacked and printed.
Example Output:
This program shows how to define a function that returns multiple values
and how to handle these return values effectively.
"""
"""
Explanation:
Output:
Hello, Alice!
Hi, Bob!
In these examples:
Here's a Python program that finds the length of a string without using any
built-in functions like len():
def find_length(input_string):
length = 0
return length
# Example usage
length_of_string = find_length(string)
Explanation:
# Get the lengths of both the main string and the substring
len_main = len(main_string)
len_sub = len(sub_string)
# Iterate over the main string up to the point where a match is possible
match = True
for j in range(len_sub):
if main_string[i + j] != sub_string[j]:
match = False
break
if match:
return True
return False
# Example usage
sub_string = "World"
if is_substring(main_string, sub_string):
else:
Explanation:
Output:
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
Explanation:
1. Addition:
o The append() method adds an element to the end of the list.
o In this example, the number 6 is added to the list.
2. Insertion:
o The insert() method inserts an element at a specified index in
the list.
o In this example, the number 99 is inserted at index 2.
3. Slicing:
o Slicing is used to get a sub-list from the original list.
o The syntax my_list[start:end] is used, where start is the
starting index (inclusive) and end is the ending index
(exclusive).
o In this example, the slice from index 1 to 3 is taken, resulting in
a sub-list.
Output:
length = len(my_list)
maximum = max(my_list)
minimum = min(my_list)
total_sum = sum(my_list)
# 5) sorted(): Return a new list with the elements sorted in ascending order
sorted_list = sorted(my_list)
Explanation:
1. len():
o Returns the number of elements in the list.
o Example: len(my_list) returns 5.
2. max():
o Returns the largest element in the list.
o Example: max(my_list) returns 50.
3. min():
o Returns the smallest element in the list.
o Example: min(my_list) returns 10.
4. sum():
o Calculates the sum of all elements in the list.
o Example: sum(my_list) returns 150.
5. sorted():
o Returns a new list with the elements sorted in ascending order.
o Example: sorted(my_list) returns [10, 20, 30, 40, 50].
Output:
This program showcases the use of five built-in functions (len, max, min,
sum, and sorted) on a list in Python, each of which serves a different
purpose in list manipulation.
Here's a Python program that creates tuples with the fields (name, age,
address, college) for at least two members, concatenates the tuples, and
prints the concatenated tuple:
Explanation:
Tuple Creation:
o Two tuples member1 and member2 are created, each
containing four elements: name, age, address, and college.
Concatenation:
o The + operator is used to concatenate member1 and member2
into a single tuple called concatenated_tuple.
Printing:
o The concatenated tuple is printed to the console.
Output:
To count the number of vowels in a string without using control flow (such
as loops or conditionals), you can use a combination of Python's string
methods and functions like sum and map. Here's an example:
def count_vowels(input_string):
vowels = "aeiouAEIOU"
# Use sum() and map() to count the number of vowels in the input_string
return vowel_count
# Example usage
vowel_count = count_vowels(string)
print(f"The number of vowels in the string is: {vowel_count}")
Explanation:
Vowels: The string vowels contains all the vowels in both lowercase
and uppercase.
Counting:
o The map() function applies the count() method for each vowel
in the vowels string.
o input_string.count(vowel) counts the occurrences of each vowel
in the input_string.
o sum() then adds up all these counts to give the total number of
vowels.
Output:
# Define a dictionary
my_dict = {
"name": "Alice",
"age": 25,
# Example usage
key_to_check = "age"
if check_key_exists(my_dict, key_to_check):
else:
Explanation:
Dictionary:
o my_dict is a dictionary with some key-value pairs (e.g.,
"name": "Alice").
Function:
o The check_key_exists() function takes two arguments: the
dictionary and the key to check.
o It uses the in operator to determine if the key exists in the
dictionary and returns True if it does, False otherwise.
Example Usage:
o The key_to_check is set to "age", and the program checks if
this key exists in my_dict.
o Depending on whether the key is found, the program prints an
appropriate message.
Output:
my_dict = {
"name": "Alice",
"age": 25,
dictionary[key] = value
# Example usage
new_key = "college"
Explanation:
Dictionary:
o my_dict is an initial dictionary containing some key-value
pairs.
Function:
o The add_key_value() function takes three arguments:
dictionary, key, and value.
o It adds the new key-value pair to the dictionary using
dictionary[key] = value.
Example Usage:
o The new_key is "college", and the new_value is "University of
Python".
o The program adds this key-value pair to my_dict.
Output:
o The updated dictionary is printed, showing the newly added
key-value pair.
Output:
Here's a Python program that sums all the values in a given dictionary:
my_dict = {
"item1": 100,
"item2": 200,
"item3": 300,
"item4": 400
def sum_values(dictionary):
return sum(dictionary.values())
# Example usage
total_sum = sum_values(my_dict)
Explanation:
Dictionary:
o my_dict is a dictionary with some items and their
corresponding numeric values.
Function:
o The sum_values() function takes a dictionary as an argument.
o It uses the values() method to retrieve all the values from the
dictionary.
o The sum() function then calculates the sum of these values.
Example Usage:
o The program calculates the sum of all the values in my_dict
and stores it in total_sum.
Output:
o The result is printed, showing the total sum of the values in the
dictionary.
Output:
This program efficiently sums all the numeric values in a dictionary using
Python's sum() function.
# Function to read words from a file, sort them, and write to another file
# Read all the words, convert them to lowercase, and split into a list
words = infile.read().lower().split()
sorted_words = sorted(words)
outfile.write(word + '\n')
# Example usage
input_file = 'input.txt'
output_file = 'output.txt'
sort_words_in_file(input_file, output_file)
print(f"Sorted words have been written to {output_file}.")
Explanation:
Important Notes:
Ensure that input.txt exists and contains the words you want to
process.
The program will create or overwrite output.txt with the sorted list of
lowercase words.
apple
banana
orange
Here's a Python program that reads each line from a file and prints each
line in reverse order:
# Function to print each line of a file in reverse order
def print_lines_in_reverse(file_name):
lines = file.readlines()
reversed_line = line.strip()[::-1]
print(reversed_line)
# Example usage
file_name = 'input.txt'
print_lines_in_reverse(file_name)
Explanation:
Reading Lines:
o Open the file using with open(file_name, 'r') as file to ensure it
is properly closed after reading.
o Use file.readlines() to read all lines from the file into a list.
Processing Lines:
o Iterate over each line in the list.
o Use line.strip() to remove any leading or trailing whitespace
(including newlines).
o Reverse the string using slicing [::-1].
o Print the reversed line.
Example Usage:
o Set file_name to the name of the file you want to read.
o Call print_lines_in_reverse(file_name) to print each line of the
file in reverse order.
Hello World
Python Programming
File Processing
Example Output:
dlroW olleH
gnimmargorP nohtyP
gnicorP eliF
This program effectively reads each line from a file, reverses the content of
each line, and prints the result. Make sure the input.txt file exists and
contains the text you want to process.
def compute_file_stats(file_name):
num_chars = 0
num_words = 0
num_lines = 0
num_lines += 1
num_chars += len(line)
num_words += len(line.split())
# Example usage
file_name = 'input.txt'
Explanation:
Initialization:
o num_chars, num_words, and num_lines are initialized to zero
to keep track of the count of characters, words, and lines
respectively.
Reading the File:
o Open the file using with open(file_name, 'r') as file to ensure
the file is properly closed after reading.
o Iterate over each line in the file using a for loop.
Counting:
o Lines: Increment num_lines for each line read.
o Characters: Use len(line) to count characters in the line and
add to num_chars.
o Words: Use line.split() to split the line into words and count
them using len(); add the count to num_words.
Output:
o Print the results for characters, words, and lines.
Hello World
Python Programming
File Processing
Example Output:
Number of characters: 52
Number of words: 6
Number of lines: 3
This program reads the file and computes the required statistics by
counting characters, words, and lines. Ensure that input.txt exists and
contains the text you want to analyze.
my_array = [1, 2, 3, 4, 5]
def display_array(arr):
arr.append(item)
print("Invalid index.")
return
arr.insert(index, item)
def reverse_array(arr):
arr.reverse()
print("Array reversed.")
# Example usage
Explanation:
1. Initial Array:
o my_array is defined with initial values [1, 2, 3, 4, 5].
2. Display Function:
o display_array() prints the current contents of the array.
3. Append Function:
o append_item() appends a new item to the end of the array
using arr.append(item).
4. Insert Function:
o insert_item() inserts a new item at a specified index using
arr.insert(index, item).
o Checks if the index is valid before inserting.
5. Reverse Function:
o reverse_array() reverses the order of items in the array using
arr.reverse().
6. Example Usage:
o The program displays the array, appends an item, inserts an
item, and reverses the array, showing the results at each step.
Output:
Item 6 appended.
Array reversed.
result = [
for i in range(len(matrix1))
return result
def transpose_matrix(matrix):
result = [
for i in range(len(matrix[0]))
]
return result
if len(matrix1[0]) != len(matrix2):
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
return result
# Example usage
matrix1 = [
[1, 2],
[3, 4]
]
matrix2 = [
[5, 6],
[7, 8]
print("Matrix 1:")
print(row)
print("\nMatrix 2:")
print(row)
# Matrix Addition
print("\nMatrix Addition:")
try:
print(row)
except ValueError as e:
print(e)
# Matrix Transposition
print("\nMatrix 1 Transposed:")
transpose_result1 = transpose_matrix(matrix1)
print(row)
print("\nMatrix 2 Transposed:")
transpose_result2 = transpose_matrix(matrix2)
print(row)
# Matrix Multiplication
print("\nMatrix Multiplication:")
try:
print(row)
except ValueError as e:
print(e)
Explanation:
1. Matrix Addition:
o Checks if the dimensions of the matrices are the same.
o Adds corresponding elements of both matrices.
2. Matrix Transposition:
o Swaps rows and columns of the matrix.
3. Matrix Multiplication:
o Checks if the number of columns in the first matrix equals the
number of rows in the second matrix.
o Multiplies matrices using the dot product of rows and columns.
Output:
Matrix 1:
[1, 2]
[3, 4]
Matrix 2:
[5, 6]
[7, 8]
Matrix Addition:
[6, 8]
[10, 12]
Matrix 1 Transposed:
[1, 3]
[2, 4]
Matrix 2 Transposed:
[5, 7]
[6, 8]
Matrix Multiplication:
[19, 22]
[43, 50]
Here's a Python program that defines a base class Shape and three
subclasses Circle, Triangle, and Square. Each subclass implements
methods to calculate its area and perimeter.
import math
class Shape:
def area(self):
def perimeter(self):
class Circle(Shape):
self.radius = radius
def area(self):
def perimeter(self):
class Triangle(Shape):
self.a = a
self.b = b
self.c = c
def area(self):
def perimeter(self):
class Square(Shape):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
# Example usage
def print_shape_info(shape):
print(f"Area: {shape.area()}")
print(f"Perimeter: {shape.perimeter()}")
circle = Circle(radius=5)
square = Square(side=4)
print("Circle:")
print_shape_info(circle)
print("\nTriangle:")
print_shape_info(triangle)
print("\nSquare:")
print_shape_info(square)
Explanation:
1. Base Class Shape:
o Defines the abstract methods area() and perimeter(). These
methods are meant to be overridden by subclasses.
2. Subclass Circle:
o Initializes with a radius.
o Implements the area() method using the formula π×radius2\pi
\times \text{radius}^2π×radius2.
o Implements the perimeter() method using the formula
2×π×radius2 \times \pi \times \text{radius}2×π×radius.
3. Subclass Triangle:
o Initializes with the lengths of the three sides: a, b, and c.
o Implements the area() method using Heron's formula.
o Implements the perimeter() method by summing the sides.
4. Subclass Square:
o Initializes with the side length.
o Implements the area() method using the formula
side2\text{side}^2side2.
o Implements the perimeter() method using the formula 4×side4
\times \text{side}4×side.
5. Example Usage:
o Creates instances of Circle, Triangle, and Square.
o Uses the print_shape_info() function to print the area and
perimeter of each shape.
Output:
Circle:
Area: 78.53981633974483
Perimeter: 31.41592653589793
Triangle:
Area: 6.0
Perimeter: 12
Square:
Area: 16
Perimeter: 16
To check whether a JSON string contains specific keys or values, you can
follow these steps:
import json
try:
data = json.loads(json_string)
if key in data:
return True
else:
return False
except json.JSONDecodeError:
print("Invalid JSON string.")
return False
try:
data = json.loads(json_string)
for v in data.values():
if v == value:
return True
return False
except json.JSONDecodeError:
return False
key_to_check = "age"
if check_key_in_json(json_string, key_to_check):
if check_value_in_json(json_string, value_to_check):
else:
Explanation:
1. check_key_in_json() Function:
o Parses the JSON string using json.loads() to convert it into a
Python dictionary.
o Checks if the specified key exists in the dictionary using the in
operator.
o Handles JSON decoding errors by catching
json.JSONDecodeError.
2. check_value_in_json() Function:
o Parses the JSON string into a Python dictionary.
o Iterates over the dictionary values to check if any value
matches the specified value.
o Handles JSON decoding errors similarly.
3. Example Usage:
o Defines a JSON string and checks for the presence of a specific
key and value using the provided functions.
o Prints results based on whether the key or value is found.
Output:
To demonstrate NumPy arrays creation using the array() function from the
NumPy library, you need to first install the NumPy library if you haven't
already. You can install it using pip:
Here’s a Python program that shows how to create NumPy arrays using
the array() function:
import numpy as np
# Create a 1D array
print("1D Array:")
print(array_1d)
# Create a 2D array
print("\n2D Array:")
print(array_2d)
# Create a 3D array
print("\n3D Array:")
print(array_3d)
print(array_float)
print(array_shape)
empty_array = np.array([[None]*3]*3)
print(empty_array)
Explanation:
1. Import NumPy:
o import numpy as np imports the NumPy library and gives it an
alias np.
2. 1D Array:
o array_1d = np.array([1, 2, 3, 4, 5]) creates a one-dimensional
array.
3. 2D Array:
o array_2d = np.array([[1, 2, 3], [4, 5, 6]]) creates a two-
dimensional array (matrix).
4. 3D Array:
o array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) creates a
three-dimensional array (tensor).
5. Array with Specific Data Type:
o array_float = np.array([1, 2, 3, 4, 5], dtype=float) creates an
array with a specified data type (float).
6. Array with Specific Shape Using Nested Lists:
o array_shape = np.array([[1, 2], [3, 4], [5, 6]]) creates an array
with a specific shape.
7. Empty Array (Uninitialized):
o empty_array = np.array([[None]*3]*3) creates an empty array
filled with None values. Note that this creates an array of
objects, and it's generally used for demonstration.
Output:
1D Array:
[1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
[1. 2. 3. 4. 5.]
Array with Specific Shape:
[[1 2]
[3 4]
[5 6]]
This program covers the basic use of the np.array() function to create
arrays of different dimensions, data types, and shapes using NumPy.
import numpy as np
print("Array:")
print(array)
# Number of dimensions (ndim)
Explanation:
1. Import NumPy:
o import numpy as np imports the NumPy library.
2. Create a Sample NumPy Array:
o array = np.array([[1, 2, 3], [4, 5, 6]]) creates a 2D NumPy array
with shape (2, 3).
3. Number of Dimensions (ndim):
o array.ndim returns the number of dimensions of the array. For
a 2D array, it returns 2.
4. Shape of the Array (shape):
o array.shape returns a tuple representing the shape of the
array. For a 2D array with 2 rows and 3 columns, it returns (2,
3).
5. Total Number of Elements (size):
o array.size returns the total number of elements in the array.
For a 2D array with 2 rows and 3 columns, it returns 6.
6. Data Type of the Elements (dtype):
o array.dtype returns the data type of the elements in the array.
For integers, it typically returns int64 or int32, depending on
the platform.
Output:
Array:
[[1 2 3]
[4 5 6]]
import numpy as np
print("Original Array:")
print(array)
# Basic Slicing
# Slice the first two rows and the first three columns
print(sliced_array)
# Integer Indexing
print(integer_indexed_array)
# Boolean Indexing
print(boolean_index)
print(array[boolean_index])
import numpy as np
print("Original Array:")
print(array)
# Basic Slicing
# Slice the first two rows and the first three columns
print(sliced_array)
# Integer Indexing
print(integer_indexed_array)
# Boolean Indexing
print(boolean_index)
Explanation:
1. Import NumPy:
o import numpy as np imports the NumPy library.
2. Create a Sample NumPy Array:
o array is a 3x4 NumPy array created with some sample values.
3. Basic Slicing:
o sliced_array = array[:2, :3] slices the array to get the first 2
rows and the first 3 columns. The result is a 2x3 sub-array.
4. Integer Indexing:
o integer_indexed_array = array[[0, 1, 2], [1, 2, 3]] selects
elements from specific positions in the array. Here, it selects
elements from positions (0,1), (1,2), and (2,3).
5. Boolean Indexing:
o boolean_index = array > 60 creates a boolean array where each
element is True if the corresponding element in array is greater
than 60.
o array[boolean_index] filters the original array to include only
elements where the condition is True.
Output:
Original Array:
[[ 10 20 30 40]
[ 50 60 70 80]
[[10 20 30]
[50 60 70]]
[ 20 70 120]
Boolean Indexing (values greater than 60):
import numpy as np
print("Array:")
print(array)
min_value = np.min(array)
max_value = np.max(array)
print(max_value)
sum_value = np.sum(array)
print(sum_value)
cumulative_sum = np.cumsum(array)
print(cumulative_sum)
xplanation:
1. Import NumPy:
o import numpy as np imports the NumPy library.
2. Create a Sample NumPy Array:
o array is a 1D NumPy array with values from 1 to 10.
3. Find the Minimum Value:
o np.min(array) returns the smallest value in the array.
4. Find the Maximum Value:
o np.max(array) returns the largest value in the array.
5. Find the Sum of All Elements:
o np.sum(array) returns the sum of all elements in the array.
6. Find the Cumulative Sum:
o np.cumsum(array) returns an array where each element is the
sum of the elements up to that position.
Output:
Array:
[ 1 2 3 4 5 6 7 8 9 10]
10
55
[ 1 3 6 10 15 21 28 36 45 55]
import pandas as pd
data = {
'Age': [24, 27, 22, 32, 29, 31, 25, 28, 26, 30],
'Salary': [70000, 80000, 65000, 90000, 55000, 60000, 62000, 67000, 71000,
69000]
df = pd.DataFrame(data)
print(df.head())
Explanation:
1. Import Pandas:
o import pandas as pd imports the Pandas library.
2. Create a Dictionary:
o data is a dictionary where each key corresponds to a list of
values. Each list contains 10 values.
3. Convert Dictionary to DataFrame:
o df = pd.DataFrame(data) converts the dictionary to a Pandas
DataFrame.
4. Apply head() Method:
o df.head() displays the first five rows of the DataFrame.
Output: