python programming bcc302
python programming bcc302
BTech
(SEM III) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING
Time: 3 Hours Total Marks: 70
Note: 1. Attempt all Sections. If require any missing data; then choose suitably.
SECTION A
Eg:
#Creating a list of squares of numbers from 1 to 5 using list
comprehension
squares = [x ** 2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
b. Differentiate between / and // operator with an example. 2 2
In Python, both the / and // operators are used for division, but they
behave differently depending on the types of operands and the desired
result.
return s
print(count ))
# library.py
def greet(name):
return f Hello, {name}!
# main.py
import library
x[0] *= 3
x[0] *= 3: This line tries to multiply the string '12' three times and assign
the result back to x[0]. In Python, the *= operator on strings
concatenates the string with itself multiple times. So, '12' * 3 results in
'121212'. Therefore, x[0] becomes '121212', and there is no error here.
x[1][1] = 'bye': This line tries to modify the second character of the
string 'hello' to 'bye'. However, strings in Python are immutable,
meaning you cannot modify them in place. Therefore, this line will raise
an error.
g. Describe about different functions of matplotlib and pandas. 2 5
Both Matplotlib and Pandas are popular libraries for data visualization
and data manipulation, respectively. Let's discuss the different functions
provided by each library:
Matplotlib:
Matplotlib is a comprehensive library for creating static, interactive, and
animated visualizations. It provides a wide range of functions for
creating plots, charts, histograms, scatterplots, and more.
Pandas:
Pandas is a powerful library for data manipulation and analysis. It
provides data structures like DataFrame and Series, along with a variety
of functions for data cleaning, transformation, aggregation, and
visualization.
SECTION B
Unpacking Tuples:
Tuple unpacking allows you to assign the elements of a tuple to
individual variables. It's a convenient way to extract values from a tuple.
Mutable Sequences:
Mutable sequences in Python are data structures that can be modified
after creation. Lists are the most common mutable sequence in Python.
String Concatenation:
String concatenation is the process of combining two or more strings
into a single string.
1. Return a list of numbers starting from the last to second item of the
list
slice1 = L[-1:-3:-1]
print(slice1) # Output: [9, 8]
2. Return a list that starts from 3rd item to second last item.
slice2 = L[2:-1]
print(slice2) # Output: [3, 4, 5, 6, 7, 8]
3. Return a list that has only even position elements of list L to list M.
M = L[1::2]
print(M) # Output: [2, 4, 6, 8]
6. Divide each element of the list by 2 and replace it with the remainder.
remainder_list = [num % 2 for num in L]
print(remainder_list) # Output: [1, 0, 1, 0, 1, 0, 1, 0, 1]
def perfect_square(number):
sqrt_num = int(number ** 0.5) # Calculate the integer square root
if sqrt_num * sqrt_num == number: # Check if the square of the
integer square root equals the original number
return number
else:
return -1
# Test cases
print(perfect_square(1)) # Output: 1
print(perfect_square(2)) # Output: -1
d. Construct a program to change the contents of the file by separating 7 4
each character by comma:
Hello!!
Output
H,e,l,l,o,!,!
# Open the input file in read mode and output file in write mode
with open("input.txt", "r") as input_file, open("output.txt", "w") as
output_file:
# Read the contents of the input file character by character
for char in input_file.read():
# Write the character followed by a comma to the output file
output_file.write(char + ",")
# input.txt
Contents of the file have been separated by comma and written to
output.txt.
#output.txt
C,o,n,t,e,n,t,s, ,o,f, ,t,h,e, ,f,i,l,e, ,h,a,v,e, ,b,e,e,n, ,s,e,p,a,r,a,t,e,d, ,b,y,
,c,o,m,m,a, ,a,n,d, ,w,r,i,t,t,e,n, ,t,o, ,o,u,t,p,u,t,.,t,x,t,
e. Construct a plot for following dataset using matplotlib : 7 5
Calorie Potassiu
Food s m fat
Meat 250 40 8
Banana 130 55 5
Avocados 140 20 3
Sweet
Potatoes 120 30 6
Spinach 20 40 1
Watermelo
n 20 32 1.5
Coconut
water 10 10 0
Beans 50 26 2
Legumes 40 25 1.5
Tomato 19 20 2.5
) returns MNGO
# Test cases
print(removenth("MANGO", 1)) # Output: MNGO
print(removenth("MANGO", 3)) # Output: MANO
def sort_words(input_str):
# Split the input string into a list of words
words = input_str.split(", ")
import re
accepted_pass = []
for i in passwords:
else:
accepted_pass.append(i)
print((" ").join(accepted_pass))
b. Explore the working of while, and for loop with examples. 7 2
Both while and for loops are control flow constructs in Python used for
iteration. They help execute a block of code repeatedly until a certain
condition is met (while loop) or until the elements of a sequence have
been exhausted (for loop).
while loop:
The while loop repeatedly executes a block of code as long as a specified
condition evaluates to True.
Syntax:
while condition:
# code block
Eg:
# Print numbers from 1 to 5 using a while loop
num = 1
while num <= 5:
print(num)
num += 1
for loop:
The for loop iterates over the elements of a sequence (such as lists,
tuples, strings, etc.) or any iterable object, executing a block of code for
each element.
Syntax:
for element in sequence:
# code block
Eg:
# Print each character of a string using a for loop
word = "Hello"
for char in word:
print(char)
ret_smaller([ [ -2, -1, 0, 0.12, 1, 2], [3, 4, 5], [6 , 7, 8, 9, 10], [11, 12,
13, 14, 15]]) returns [3,4,5]
ret_smaller([ [ -2, -
9, 10], [11, 12, 13, 14, 15]]) returns [6 , 7, 8, 9, 10]
def ret_smaller(l):
# Initialize the smallest list variable with the first sublist
smallest_list = l[0]
return smallest_list
nested_list2 = [[-2, -1, 0, 0.12, 1, 2], ['a', 'b', 'c', 'd', 3, 4, 5], [6, 7, 8, 9,
10], [11, 12, 13, 14, 15]]
result2 = ret_smaller(nested_list2)
print(result2) # Output: [6, 7, 8, 9, 10]
# Function to filter all the strings that contain any of the specified nouns
def filter_strings_containing_nouns(text):
nouns = {'Agra', 'Ramesh', 'Tomato', 'Patna'}
return [word for word in text if any(noun in word for noun in nouns)]
# Test text
text = ["apple", "123", "Agra", "banana", "Ramesh", "tomato", "1234",
"Patna", "orange"]
# Apply filters
filtered_numbers = filter_numbers(text)
filtered_vowel_strings = filter_strings_starting_with_vowel(text)
filtered_noun_strings = filter_strings_containing_nouns(text)
# Print results
print("Filtered numbers:", filtered_numbers)
print("Strings starting with a vowel:", filtered_vowel_strings)
print("Strings containing specified nouns:", filtered_noun_strings)
Given two integer numbers, return their product only if the product
is equal to or lower than one zero
def number_to_text(number):
# Define a dictionary to map numbers to text
num_to_text = {
'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four',
'5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'
}
def convert_numbers_to_text(file_path):
# Read the content of the file
with open(file_path, 'r') as file:
content = file.read()
def print_words_with_digits(file_path):
# Read the content of the file
with open(file_path, 'r') as file:
content = file.read()
import pandas as pd
import matplotlib.pyplot as plt
def press_plus():
entry.insert(END,"+")
def press_minus():
entry.insert(END,"-")
def press_multiply():
entry.insert(END,"*")
def press_divide():
entry.insert(END,"/")
def press_equal():
global expression
expression = entry.get()
entry.delete(0,END)
entry.insert(0,eval(expression))
def press_clear():
entry.delete(0,END)
#Add widgets
# create a menubar
menubar = Menu(root)
root.config(menu=menubar)
# create a menu
file_menu = Menu(menubar)
# add a menu item to the menu
file_menu.add_command(
label='Exit',
command=root.destroy
)
# add the File menu to the menubar
menubar.add_cascade(
label="File",
menu=file_menu
)
#Labels from 0 to 2
label_0 = Label(root, text="0",bg="#333333",fg="white",font=("Times
New Roman",12))
label_1 = Label(root, text="1",bg="#333333",fg="white",font=("Times
New Roman",12))
label_2 = Label(root, text="2",bg="#333333",fg="white",font=("Times
New Roman",12))
#Buttons from 0 to 2, +
button_0 =
Button(root,text="0",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_0)
button_1 =
Button(root,text="1",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_1)
button_2 =
Button(root,text="2",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_2)
button_3 =
Button(root,text="3",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_3)
button_4 =
Button(root,text="4",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_4)
button_5 =
Button(root,text="5",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_5)
button_6 =
Button(root,text="6",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_6)
button_7 =
Button(root,text="7",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_7)
button_8 =
Button(root,text="8",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_8)
button_9 =
Button(root,text="9",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_9)
button_plus =
Button(root,text="+",bg="#A73278",fg="white",borderless=1,font=("
Times New Roman",12),command=press_plus)
button_minus = Button(root,text="-
",bg="#A73278",fg="white",borderless=1,font=("Times New
Roman",12),command=press_minus)
button_multiply =
Button(root,text="*",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_multiply)
button_divide =
Button(root,text="/",bg="#A73278",fg="white",borderless=1,font=("T
imes New Roman",12),command=press_divide)
button_equal =
Button(root,text="=",bg="#A73278",fg="white",borderless=1,font=("
Times New Roman",12),command=press_equal)
button_clear =
Button(root,text="Clear",bg="#A73278",fg="white",borderless=1,font
=("Times New Roman",12),command=press_clear)
button_1.grid(row=1,column=0)
button_2.grid(row=1,column=1)
button_3.grid(row=1,column=2)
button_4.grid(row=2,column=0)
button_5.grid(row=2,column=1)
button_6.grid(row=2,column=2)
button_7.grid(row=3,column=0)
button_8.grid(row=3,column=1)
button_9.grid(row=3,column=2)
button_0.grid(row=4,column=0,columnspan=3)
button_plus.grid(row=5,column=0)
button_minus.grid(row=5,column=1)
button_multiply.grid(row=5,column=2)
button_divide.grid(row=6,column=0)
button_equal.grid(row=6,column=1)
button_clear.grid(row=6,column=2)
root.mainloop()