[go: up one dir, main page]

0% found this document useful (0 votes)
170 views9 pages

Sem (Iv) (Aktu) Theory Examination 2023-24 Solution

The document covers various Python programming concepts, including dynamic typing, list definitions, functions, file handling, and data visualization using matplotlib. It provides examples of code for removing duplicates from a list, calculating the sum of numbers in a list, finding the LCM of two numbers, and manipulating strings and dictionaries. Additionally, it explains advanced topics like generators, NumPy random number generation, and pandas DataFrames.

Uploaded by

rishabhyadav7923
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
170 views9 pages

Sem (Iv) (Aktu) Theory Examination 2023-24 Solution

The document covers various Python programming concepts, including dynamic typing, list definitions, functions, file handling, and data visualization using matplotlib. It provides examples of code for removing duplicates from a list, calculating the sum of numbers in a list, finding the LCM of two numbers, and manipulating strings and dictionaries. Additionally, it explains advanced topics like generators, NumPy random number generation, and pandas DataFrames.

Uploaded by

rishabhyadav7923
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

SEM IV THEORY EXAMINATION 2023-24

PYTHON PROGRAMMING

Explain the concept of dynamic typing in Python with an example.

Dynamic typing in Python means that the type of a variable is determined at runtime, not at compile time.
This allows you to assign different types of data to the same variable without explicitly declaring its type.​

x = 10 # x is an integer​
print(x) # Output: 10​

x = "Hello" # x is now a string​
print(x) # Output: Hello

In this example, the variable x is first assigned an integer value and then a string value. Python dynamically
changes the type of x based on the value assigned to it.

Explain how to define a list in Python. Write a Python program to remove duplicates

A list in Python is defined by enclosing elements in square brackets [], separated by commas.

Example
my_list = [1, 2, 2, 3, 4, 4, 5]

Program to remove duplicates


my_list = [1, 2, 2, 3, 4, 4, 5]​
result = list(set(my_list))​

print(result) # Output: [1, 2, 3, 4, 5]

Explain the concept of functions in Python. Write a function that takes a list of numbers and returns the sum
of all the numbers in the list.

A function is a block of reusable code that performs a specific task. Functions are defined using the def
keyword, followed by the function name and parentheses ().

Made with ☘️ @rishabh.real


def sum_of_list(numbers):​
return sum(numbers)​

my_list = [1, 2, 3, 4, 5]​
result = sum_of_list(my_list)​
print(result) # Output: 15

Write a Python program to read a file named "ABC.txt" and count the number of lines, words, and characters
in the file.

with open('ABC.txt', 'r') as file:​


lines = file.readlines()​
num_lines = len(lines)​
num_words = sum(len(line.split()) for line in lines)​
num_chars = sum(len(line) for line in lines)​


print(f"Lines: {num_lines}, Words: {num_words}, Characters: {num_chars}")

Explain the basic usage of matplotlib for plotting graphs. Write a Python program to plot a simple line graph
showing the relationship between​

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

Matplotlib is a plotting library in Python used for creating static, animated, and interactive visualizations. The
basic steps to create a plot are:​

1.​ Import the matplotlib.pyplot module.


2.​ Define the data to be plotted.
3.​ Use functions like plot() to create the plot.
4.​ Use show() to display the plot.

Python program to plot a simple line graph


import matplotlib.pyplot as plt​

x = [1, 2, 3, 4, 5]​
y = [1, 4, 9, 16, 25]​

plt.plot(x, y)​
plt.xlabel('x-axis')​
plt.ylabel('y-axis')​
plt.title('Simple Line Graph')​
plt.show()

Made with ☘️ @rishabh.real


Explain for loop and while loop used in python using example

Already answered in 2022-23 paper

Write a python program to find the LCM of two numbers

def find_lcm(a, b):​


# Find the greater number​
greater = max(a, b)​

while True:​
if greater % a == 0 and greater % b == 0:​
lcm = greater​
break​
greater += 1​

return lcm​

# Input two numbers​
num1 = int(input("Enter first number: "))​
num2 = int(input("Enter second number: "))​

# Find and print the LCM​
lcm = find_lcm(num1, num2)​
print(f"The LCM of {num1} and {num2} is {lcm}")

Write a program that takes two strings and checks for common letters in both the strings.

string1 = input("Enter the first string: ").lower()​


string2 = input("Enter the second string: ").lower()

common_letters = []​

for char in string1:​
if char in string2 and char not in common_letters:
common_letters.append(char)​

print(f"Common letters: {', '.join(common_letters)}")

Write a Python Program to find the sum of all the items in a dictionary.

# Example dictionary​
d = {'A': 100, 'B': 540, 'C': 239}​

# Calculate and print the sum​
total_sum = sum(d.values())​
print(f"The sum of all the items in the dictionary is: {total_sum}")

Made with ☘️ @rishabh.real


Explain the concept of a set in Python and its characteristics. How elements are added or removed in a set.

A set in Python is an unordered collection of unique elements. Sets are mutable, meaning they can be
changed after they are created. The key characteristics of sets are:

●​ Unordered: The elements in a set do not have a specific order.


●​ Unique: Sets cannot contain duplicate elements.
●​ Mutable: Elements can be added or removed from a set.

Elements can be added to a set using the add() method for a single element or the update() method for
multiple elements.

# Creating a set​
my_set = {1, 2, 3}​

# Adding elements​
my_set.add(4)​
my_set.update([5, 6])

Elements can be removed using the remove() or discard() methods. The remove() method raises an error if
the element is not found, while discard() does not.

# Creating a set​
my_set = {1, 2, 3}​

# Removing elements​
my_set.remove(3)​
my_set.discard(7) # No error even if 7 is not in the set

Explain how lambda functions can be used within a list comprehension. Write a Python program that uses a
lambda function within a list comprehension to convert a list of temperatures in Celsius to Fahrenheit.

Lambda functions are anonymous functions defined using the lambda keyword. They can be used within list
comprehensions to apply a function to each element in a list.​

# List of temperatures in Celsius​


celsius_temps = [0, 10, 20, 30, 40]​

# Convert to Fahrenheit using lambda and list comprehension​
fahrenheit_temps = [(lambda c: (9/5) * c + 32)(c) for c in celsius_temps]​

print(fahrenheit_temps) # Output: [32.0, 50.0, 68.0, 86.0, 104.0]

Made with ☘️ @rishabh.real


Explain different file opening modes and also write a Python Program to read a file and capitalize the first
letter of every word in the file.

File Opening Modes:

r Open text file for reading. Raises an I/O error if the file does not exist.

w Open the file for writing. Truncates the file if it already exists. Creates a new file if it does not exist.

a Open the file for writing. The data being written will be inserted at the end of the file. Creates a new
file if it does not exist.

r+ Open the file for reading and writing. Raises an I/O error if the file does not exist.

w+ Open the file for reading and writing. Truncates the file if it already exists. Creates a new file if it
does not exist.

a+ Open the file for reading and writing. The data being written will be inserted at the end of the file.
Creates a new file if it does not exist.

rb Open the file for reading in binary format. Raises an I/O error if the file does not exist.

wb Open the file for writing in binary format. Truncates the file if it already exists. Creates a new file if it
does not exist.

ab Open the file for appending in binary format. Inserts data at the end of the file. Creates a new file if
it does not exist.

rb+ Open the file for reading and writing in binary format. Raises an I/O error if the file does not exist.

wb+ Open the file for reading and writing in binary format. Truncates the file if it already exists. Creates
a new file if it does not exist.

ab+ Open the file for reading and appending in binary format. Inserts data at the end of the file. Creates
a new file if it does not exist.

Program
with open('example.txt', 'r') as file:​
content = file.read()​
capitalized_content = ' '.join(word.capitalize() for word in content.split())​

with open('example.txt', 'w') as file:​
file.write(capitalized_content)

Made with ☘️ @rishabh.real


What do you mean by generators in Python? How is it created in Python?

Generators are a type of iterable, like lists or tuples, but they do not store all their values in memory at once.
Instead, they generate values on the fly using the yield keyword. This makes them memory efficient for large
datasets.

Generators are created using functions that contain the yield keyword. When the function is called, it returns
a generator object.

def simple_generator():​
yield 1​
yield 2​
yield 3​

# Using the generator​
gen = simple_generator()​
for value in gen:​
print(value) # Output: 1 2 3

Describe how to generate random numbers using NumPy. Write a Python program to create an array of 5
random integers between 10 and 50.

NumPy provides the random module to generate random numbers. The randint() function can be used to
generate random integers within a specified range.

import numpy as np​



# Generate an array of 5 random integers between 10 and 50​
random_array = np.random.randint(10, 51, 5)​

print(random_array) # Output will vary, e.g., [12, 34, 23, 45, 19]

Made with ☘️ @rishabh.real


Explain the concept of DataFrame in pandas. Write a Python program to create a DataFrame from a
dictionary and print it.

A DataFrame is a two-dimensional, size-mutable, and


potentially heterogeneous tabular data structure with
labeled axes (rows and columns). It is similar to a
spreadsheet or SQL table.

import pandas as pd​



data = {​
'Name': ['Alice', 'Bob', 'Charlie'],​
'Age': [25, 30, 35],​
'City': ['New York', 'Los Angeles', 'Chicago']​
}​

df = pd.DataFrame(data)​
print(df)

Output

Name Age City​


0 Alice 25 New York​
1 Bob 30 Los Angeles​
2 Charlie 35 Chicago

Made with ☘️ @rishabh.real


SHORT ANSWERS

Give the difference between = and is operator.

The == operator helps us compare the equality of objects. The is operator helps us check whether different
variables point towards a similar object in the memory

How do we print the character of a given ASCII value in Python?

You can use the chr() function to convert an ASCII value to its corresponding character.​

ascii_value = 65​
character = chr(ascii_value)​
print(character) # Output: A

Can you use else with a for loop? If so, when is it executed?

Yes, you can use else with a for loop in Python. The else block is executed when the loop has exhausted
iterating over the items, i.e., when the loop completes normally without encountering a break statement.​

for i in range(3):​
print(i)​
else:​
print("Loop completed") # This will be executed after the loop finishes

What will be the output of the following Python code?​

I = [1, 0, 0, 2, 'hi', ',', []]​


print(list(filter(bool, I)))

[1, 2, 'hi', ',']

Describe the purpose of the split() method in string manipulation.

The split() method is used to split a string into a list of substrings based on a specified delimiter. If no
delimiter is specified, it defaults to splitting on whitespace.​

text = "Hello, world! How are you?"​


words = text.split() # Splits on whitespace​
print(words) # Output: ['Hello,', 'world!', 'How', 'are', 'you?']​

parts = text.split(',') # Splits on comma​
print(parts) # Output: ['Hello', ' world! How are you?']

What does the readline() function return when it reaches the end of a file?

The readline() function returns an empty string ('') when it reaches the end of a file.

Made with ☘️ @rishabh.real


Which function is used to create an identity matrix in NumPy?

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

import numpy as np​



identity_matrix = np.eye(3) # Creates a 3x3 identity matrix​
print(identity_matrix)

[[1. 0. 0.]​
[0. 1. 0.]​
[0. 0. 1.]]

Made with ☘️ @rishabh.real

You might also like