0% found this document useful (0 votes)
4 views

Python

Uploaded by

pagalbaba.ji2000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python

Uploaded by

pagalbaba.ji2000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

BTECH (SEM IV) THEORY EXAMINATION 2023-24

PYTHON PROGRAMMING BCC 402

Solution
Section A

1 a. == checks for value equality, while is checks for object identity (if they refer to the same object in
memory).

b. Use chr() function. For example, chr(65) returns 'A'.

C. Yes, you can use else with a for loop in Python. The else block is executed after the loop completes
normally, meaning it doesn't encounter a break statement.

d. [1, 2, ' hi']

e. The split() method in Python is used to divide a string into a list of substrings based on a specified
delimiter (by default, any whitespace). It splits the string wherever the delimiter occurs and returns the
resulting substrings as list elements.

f. When readline() reaches the end of a file, it returns an empty string ''.

g. The numpy.eye() function is used to create an identity matrix in NumPy.

Section B

2 a. Dynamic typing in Python means that the type of a variable is determined at runtime, rather than at
compile-time. This allows variables to change their type as the program executes, based on the value
that is assigned to them. In contrast to statically typed languages, where the type of a variable must be
declared and cannot change, Python variables are more flexible.

x = 10 # x is an integer

print(type(x)) # Output: <class 'int'>

x = "Hello" # Now x is a string

print(type(x)) # Output: <class 'str'>

x = [1, 2, 3] # Now x is a list


print(type(x)) # Output: <class 'list'>

Explanation:

1. Initial Assignment:

o x is first assigned the value 10. Python dynamically determines that x is an integer, so it
is stored as an int type.

2. Reassignment:

o The variable x is then reassigned the string value "Hello". Python no longer considers x
an integer; instead, it is now a string (str type).

3. Further Reassignment:

o Finally, x is reassigned a list [1, 2, 3]. Python now treats x as a list (list type).

Key Points:

No Type Declaration: Python does not require you to declare the type of a variable. The type is
inferred from the assigned value.

Type Flexibility: A variable can be reassigned to values of different types during the program's
execution, and Python will adjust accordingly.

Memory Efficiency: Dynamic typing can make Python more flexible and easier to write but may
lead to less memory-efficient code, as the type of variables can change frequently.

Implications:

Dynamic typing offers great flexibility, making Python easier and faster to write code in, especially for
quick prototyping or scripting. However, this flexibility also means that Python programs might be more
prone to type-related errors if not carefully managed, as type mismatches can occur at runtime. For this
reason, understanding and effectively managing dynamic typing is important for writing robust Python
code.

2B.

In Python, a list is a collection of items that are ordered, changeable (mutable), and allow duplicate
elements. Lists are defined using square brackets [], and items within the list are separated by commas.

# Defining a list of integers

numbers = [1, 2, 3, 4, 5]

# Defining a list of strings


fruits = ['apple', 'banana', 'cherry']

# Defining a mixed list (with different data types)

mixed_list = [1, "apple", 3.5, True]

Characteristics of Python Lists:

Ordered: The items in a list have a defined order, and that order will not change unless explicitly
changed.

Mutable: Lists can be modified after they are created. You can add, remove, or change items in
a list.

Allows Duplicates: Lists can contain duplicate values.

Program to Remove Duplicates from a List

To remove duplicates from a list, one common approach is to convert the list to a set, which inherently
removes duplicates because sets do not allow duplicate elements. After that, you can convert the set
back to a list if you need to maintain the list format.

# Define a list with duplicates

original_list = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 9, 9]

# Remove duplicates by converting the list to a set

unique_set = set(original_list)

# Convert the set back to a list

unique_list = list(unique_set)

# Sort the list to maintain the original order

unique_list.sort()

# Print the resulting list

print("Original List:", original_list)

print("List after removing duplicates:", unique_list)

Output of the Program:

Original List: [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 9, 9]


List after removing duplicates: [1, 2, 3, 4, 5, 6, 7, 8, 9]

2C . Concept of Functions in Python

In Python, a function is a reusable block of code that performs a specific task. Functions help
organize and modularize code, making it more readable, maintainable, and reusable. They allow
you to encapsulate code into a single entity, which can then be called and executed whenever
needed.

Key Components of a Function:

1. Function Definition: This is where you define what the function does. It starts with the
def keyword, followed by the function name and parentheses. Inside the parentheses, you
can specify parameters (input values) that the function accepts.
2. Function Body: The indented block of code following the function definition, which
contains the statements that define what the function does.
3. Return Statement: A function can return a value using the return statement. This is
optional; if no return is specified, the function returns None by default.
4. Function Call: To execute a function, you use its name followed by parentheses. If the
function requires arguments, you pass them inside the parentheses.

Explanation of the Function:

1. Function Name:

o sum_of_numbers is the name of the function. It should be descriptive of the task it


performs.

2. Parameters:

o numbers is a parameter that represents the input to the function. It is expected to be a


list of numerical values.

3. Function Body:

o The function initializes a variable total to 0.

o It then iterates over each number in the list numbers, adding each number to total.

o After the loop, the function returns the sum of the numbers.

4. Return Value:

o The return statement provides the sum of the numbers as the output of the function.

2 D. To read a file named ABC.txt and count the number of lines, words, and characters, you can use the
following Python program. This program will open the file, read its contents, and then use loops and
string methods to perform the counting
def count_file_contents(filename):

# Initialize counters

num_lines = 0

num_words = 0

num_characters = 0

try:

# Open the file in read mode

with open(filename, 'r') as file:

# Read through each line in the file

for line in file:

# Increment line counter

num_lines += 1

# Increment character counter (including newline characters)

num_characters += len(line)

# Split the line into words and increment word counter

words = line.split()

num_words += len(words)

except FileNotFoundError:

print(f"The file {filename} was not found.")

return
# Print the results

print(f"Number of lines: {num_lines}")

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

print(f"Number of characters: {num_characters}")

# Specify the filename

filename = 'ABC.txt'

# Call the function with the filename

count_file_contents(filename)

2E. Matplotlib is a popular Python library used for creating static, animated, and interactive
visualizations. The most common use of Matplotlib is to create plots and graphs to visualize data.

Basic Components:

1. Importing Matplotlib:

o Typically, you start by importing the pyplot module from Matplotlib, which provides a
MATLAB-like interface for plotting.

2. Creating Data:

o Define the data you want to plot, usually in the form of lists or arrays.

3. Creating a Plot:

o Use functions like plot(), scatter(), bar(), etc., to create different types of plots.

4. Customizing the Plot:

o Customize the plot by adding titles, labels, legends, and adjusting other visual elements.

5. Displaying the Plot:

o Use show() to display the plot in a window or save it using savefig().

Python Program to Plot a Simple Line Graph


between x = [1, 2, 3, 4, 5] and y = [1, 4, 9, 16, 25].

python

Copy code

import matplotlib.pyplot as plt

# Define the data

x = [1, 2, 3, 4, 5]

y = [1, 4, 9, 16, 25]

# Create a line plot

plt.plot(x, y, marker='o', linestyle='-', color='b', label='x^2')

# Add a title

plt.title('Line Graph of y = x^2')

# Add x and y axis labels

plt.xlabel('x values')

plt.ylabel('y values')

# Add a legend

plt.legend()

# Show the plot

plt.show()

Explanation
1. Importing Matplotlib:

o import matplotlib.pyplot as plt: Imports the pyplot module from Matplotlib, giving it the
alias plt.

2. Defining Data:

o x and y are lists containing the x and y values, respectively.

3. Creating a Plot:

o plt.plot(x, y, marker='o', linestyle='-', color='b', label='x^2'):

x and y are plotted against each other.

marker='o' specifies that each data point should be marked with a circle.

linestyle='-' specifies that the data points should be connected by a line.

color='b' sets the color of the line to blue.

label='x^2' assigns a label to the plot for use in the legend.

4. Customizing the Plot:

o plt.title('Line Graph of y = x^2'): Sets the title of the graph.

o plt.xlabel('x values'): Sets the label for the x-axis.

o plt.ylabel('y values'): Sets the label for the y-axis.

o plt.legend(): Displays the legend based on the label provided in the plot() function.

5. Displaying the Plot:

o plt.show(): Displays the plot in a window. This is the final step and will render the graph
on your screen.

Running the Program

To run this program:

1. Save the code in a file, for example, plot_graph.py.

2. Ensure you have Matplotlib installed. If not, you can install it using pip:

pip install matplotlib

python plot_graph.py
Section C

3A. for and while Loops in Python

Loops in Python allow you to execute a block of code repeatedly. There are two main types of loops in
Python: for loops and while loops.

for Loop

The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) and execute a
block of code for each item in the sequence. It is commonly used when you know in advance how many
times you need to execute a block of code.

for variable in sequence:

# Code to execute

Example

# Define a list of fruits

fruits = ['apple', 'banana', 'cherry']

# Iterate over the list using a for loop

for fruit in fruits:

print(fruit)

output:

apple

banana

cherry

3B. import math

def lcm(a, b):


"""

This function returns the Least Common Multiple (LCM) of two integers.

Parameters:

a (int): First integer

b (int): Second integer

Returns:

int: The LCM of a and b

"""

# Compute the Greatest Common Divisor (GCD)

gcd = math.gcd(a, b)

# Compute the Least Common Multiple (LCM) using the formula

lcm_value = abs(a * b) // gcd

return lcm_value

# Input: Two integers

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

# Compute and display the LCM

result = lcm(num1, num2)

print(f"The LCM of {num1} and {num2} is: {result}")


4 a. To write a Python program that takes two strings and checks for common letters in both strings, you
can use set operations -by-step
approach:

1. Read the input strings.

2. Convert the strings to sets of characters.

3. Find the intersection of these sets to get the common characters.

4. Print the common characters.

def common_letters(str1, str2):

"""

This function finds and returns the common letters between two strings.

Parameters:

str1 (str): The first string

str2 (str): The second string

Returns:

set: A set of common letters

"""

# Convert strings to sets of characters

set1 = set(str1)

set2 = set(str2)

# Find the intersection of both sets

common_chars = set1.intersection(set2)
return common_chars

# Input: Two strings

first_string = input("Enter first string: ")

second_string = input("Enter second string: ")

# Compute the common letters

common_chars = common_letters(first_string, second_string)

# Print the common letters

print("The common letters are:")

for char in sorted(common_chars):

print(char)

4B. To find the sum of all the values in a dictionary, you can use Python's built-in functions and
methods. Specifically, you can use the values() method to get the values from the dictionary and then
use the sum() function to compute the total.

def sum_dictionary_values(d):

"""

This function calculates the sum of all values in a dictionary.

Parameters:

d (dict): The dictionary whose values need to be summed

Returns:

int: The sum of all values in the dictionary


"""

# Get the values from the dictionary and compute the sum

total_sum = sum(d.values())

return total_sum

# Define a dictionary

d = {'A': 100, 'B': 540, 'C': 239}

# Compute the sum of all values

result = sum_dictionary_values(d)

# Print the result

print(f"The sum of all items in the dictionary is: {result}")

5 a. Concept of a Set in Python

A set in Python is an unordered collection of unique elements. Sets are a built-in data type that provide
functionality for storing and manipulating groups of items without duplicates.

Characteristics of Sets

1. Unordered: Sets do not maintain any particular order of elements. The order of elements can
change when they are added or removed.

2. Unique Elements: Sets automatically ensure that all elements are unique. Duplicate elements
are not allowed.

3. Mutable: Sets are mutable, meaning you can add or remove elements after the set has been
created.

4. No Indexing: Unlike lists or tuples, sets do not support indexing, slicing, or other sequence-like
behavior.
5. Hashable Elements: Elements of a set must be hashable, which means they must be immutable
(e.g., numbers, strings, tuples). Lists or other sets cannot be added to a set.

Creating a Set

create a set using curly braces {} or the set() constructor.

# Creating a set using curly braces

my_set = {1, 2, 3, 4}

# Creating a set using the set() constructor

another_set = set([5, 6, 7, 8])

Adding Elements to a Set:

# Define a set

my_set = {1, 2, 3}

# Add a single element

my_set.add(4)

# Add another element

my_set.add(2) # 2 is already in the set, so it will not be added again

print(my_set) # Output: {1, 2, 3, 4}

Removing Elements from a Set

You can remove elements from a set using the remove(), discard(), or pop() methods.

1. remove(element): Removes the specified element. If the element is not found, it raises a
KeyError.

2. discard(element): Removes the specified element if it exists. If the element is not found, it does
nothing (no error is raised).
3. pop(): Removes and returns an arbitrary element from the set. Since sets are unordered, you
cannot specify which element to remove.

# Define a set

my_set = {1, 2, 3, 4}

# Remove a specific element

my_set.remove(2) # Raises KeyError if 2 is not in the set

# Remove an element without raising an error if the element is not found

my_set.discard(5) # 5 is not in the set, so nothing happens

# Remove and return an arbitrary element

removed_element = my_set.pop()

print(my_set) # Output: {1, 3, 4} or some other set without the removed element

print(f"Removed element: {removed_element}")

5B. Lambda Functions: Lambda functions in Python are anonymous functions defined using the lambda
keyword. They are often used for short, throwaway functions and are typically used in situations where
a function is needed temporarily.

List Comprehensions: List comprehensions provide a concise way to create lists. They consist of an
expression followed by a for clause and optional if clauses.

Python Program Example

lambda function within a list comprehension to convert a


list of temperatures from Celsius to Fahrenheit:

Conversion Formula: Fahrenheit=9/5×Celsius+32

# List of temperatures in Celsius


celsius_temperatures = [0, 10, 20, 30, 40]

# Convert Celsius to Fahrenheit using lambda function within a list comprehension

fahrenheit_temperatures = [(lambda c: (9/5) * c + 32)(temp) for temp in celsius_temperatures]

# Print the results

print("Celsius temperatures:", celsius_temperatures)

print("Fahrenheit temperatures:", fahrenheit_temperatures)

6B. File Opening Modes in Python

When opening files in Python, you can specify the mode in which the file should be opened.
Different modes provide different types of access to the file's content. Here are the most
commonly used file opening modes:

1. 'r' (Read Mode):


o Opens the file for reading.
o The file pointer is placed at the beginning of the file.
o If the file does not exist, it raises a FileNotFoundError.
2. 'w' (Write Mode):
o Opens the file for writing.
o If the file exists, it truncates (empties) the file.
o If the file does not exist, it creates a new file.
3. 'a' (Append Mode):
o Opens the file for appending.
o Data is written at the end of the file.
o If the file does not exist, it creates a new file.
4. 'b' (Binary Mode):
o Opens the file in binary mode.
o Used with other modes (e.g., 'rb', 'wb') to handle binary data (e.g., images).
5. 'r+' (Read and Write Mode):
o Opens the file for both reading and writing.
o The file pointer is placed at the beginning of the file.
o If the file does not exist, it raises a FileNotFoundError.
6. 'x' (Exclusive Creation Mode):
o Opens the file for exclusive creation.
o If the file already exists, it raises a FileExistsError.
Python Program to Capitalize the First Letter of Every Word in a File

ds a file and capitalizes the first letter of every word in the file.
It writes the modified content back to the file or to a new file

def capitalize_first_letter(file_path, output_path):

"""

This function reads a file, capitalizes the first letter of every word,

and writes the modified content to another file.

Parameters:

file_path (str): Path to the input file

output_path (str): Path to the output file where the modified content will be saved

"""

try:

# Open the input file for reading

with open(file_path, 'r') as file:

# Read the content of the file

content = file.read()

# Capitalize the first letter of every word

capitalized_content = ' '.join(word.capitalize() for word in content.split())

# Open the output file for writing

with open(output_path, 'w') as file:

# Write the modified content to the output file


file.write(capitalized_content)

print("File has been processed and saved to", output_path)

except FileNotFoundError:

print(f"Error: The file {file_path} does not exist.")

except Exception as e:

print(f"An error occurred: {e}")

# Define the input and output file paths

input_file_path = 'input.txt' # Replace with the path to your input file

output_file_path = 'output.txt' # Replace with the path to your output file

# Call the function to process the file

capitalize_first_letter(input_file_path, output_file_path)

6B. Generators in Python

Generators are a type of iterable, like lists or tuples, but they generate values on the fly and only
when needed. They are a more memory-efficient way to handle large sequences of data because
they yield items one at a time and do not require all the data to be stored in memory at once.

Characteristics of Generators

1. Lazy Evaluation: Generators produce items one at a time and only when requested. This
is known as lazy evaluation or on-the-fly computation.
2. Memory Efficient: Since they generate values one at a time and do not store the entire
sequence in memory, they are particularly useful for large datasets or streams of data.
3. State Preservation: Generators maintain their state between yields. They remember
where they left off and can continue generating values from that point.
4. Simpler Code: Generators can simplify the code needed for iterating over sequences,
especially when the logic for producing elements is complex.

Creating Generators

Generators can be created in two main ways:

1. Generator Functions:
o A generator function uses the yield keyword to produce values. Each call to yield
produces the next value in the sequence.
o Unlike regular functions, which return a single value, generator functions return a
generator object that can be iterated over.
2. Generator Expressions:
o Generator expressions are similar to list comprehensions but use parentheses
instead of square brackets. They produce values on the fly and are more memory-
efficient than creating a list.

7A. NumPy provides a comprehensive suite of functions for generating random numbers. These
functions are part of the numpy.random module and allow for generating random numbers in
various distributions and ranges.

Commonly Used Functions:

1. numpy.random.randint(low, high=None, size=None)


o Generates random integers from a specified range.
o low is the lowest integer to be drawn (inclusive).
o high is the upper bound (exclusive) if provided. If not provided, the range is from
0 to low.
o size specifies the shape of the output array.
2. numpy.random.random(size=None)
o Generates random floats in the half-open interval [0.0, 1.0).
o size specifies the shape of the output array.
3. numpy.random.uniform(low=0.0, high=1.0, size=None)
o Generates random floats from a uniform distribution over a specified interval.
o low and high specify the range.
4. numpy.random.randn(d0, d1, ..., dn)
o Generates samples from a standard normal distribution (mean=0, variance=1).
o The dimensions (d0, d1, ..., dn) specify the shape of the output array.

import numpy as np

# Generate an array of 5 random integers between 10 and 50

random_integers = np.random.randint(10, 51, size=5)


# Print the result

print("Array of 5 random integers between 10 and 50:")

print(random_integers)

7B. Concept of DataFrame in Pandas

DataFrame is a two-dimensional, size-mutable, and potentially heterogeneous tabular data


structure provided by the pandas library in Python. It is similar to a spreadsheet or SQL table,
and it is one of the most commonly used data structures in data analysis and manipulation.

Key Characteristics of DataFrames

1. Rows and Columns:


o DataFrames are organized into rows and columns. Each column can be of a
different data type (e.g., integers, floats, strings).
2. Indexing:
o DataFrames have row and column indices, which can be customized. The default
index is a sequence of integers starting from 0.
3. Data Alignment:
o DataFrames automatically align data based on row and column labels, which
makes it easier to work with data from different sources.
4. Flexible Data Handling:
o You can perform a wide range of operations on DataFrames, such as filtering,
grouping, aggregating, and joining datasets.
5. Missing Data Handling:
o Pandas provides tools for handling missing or NaN (Not a Number) values
efficiently.

Creating a DataFrame from a Dictionary

A common way to create a DataFrame is from a dictionary where keys are column names and
values are lists of column data.

import pandas as pd

# Create a dictionary with sample data

data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],

'Age': [25, 30, 35, 40],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']

# Create a DataFrame from the dictionary

df = pd.DataFrame(data)

# Print the DataFrame

print("DataFrame created from dictionary:")

print(df)

You might also like