0% found this document useful (0 votes)
3 views13 pages

FPP Unit 3 To 6 Question Answer

The document contains a comprehensive question bank for the Fundamental Python Programming course at Zeal College of Engineering and Research for the academic year 2024-25. It includes various programming exercises covering topics such as string manipulation, list and tuple operations, set and dictionary methods, and function definitions. Each question is accompanied by a solution demonstrating the required Python code.

Uploaded by

Amit Pujari
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)
3 views13 pages

FPP Unit 3 To 6 Question Answer

The document contains a comprehensive question bank for the Fundamental Python Programming course at Zeal College of Engineering and Research for the academic year 2024-25. It includes various programming exercises covering topics such as string manipulation, list and tuple operations, set and dictionary methods, and function definitions. Each question is accompanied by a solution demonstrating the required Python code.

Uploaded by

Amit Pujari
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/ 13

ZEAL EDUCATION SOCIETY’S

ZEAL COLLEGE OF ENGINEERING AND RESEARCH


NARHE │PUNE -41 │ INDIA

Record No.: ZCOER-ACAD/R/16M Revision: 00 Date:25/05/2025

Unit 3 Question Bank

Department: FY BTech Semester: II Academic Year: 2024-25


Class: FY Comp / IT / AI-DS / AI-ML Div. : A,B,C
Date: 25.05.2025
Course: Fundamental Python Programming
Q.
Question
No.
Write a Python program to Reverse a String.

Solution:
1.
str1 = 'MAHARASHTRA'
str2 = str1[::-1]
print(str2)
Write a Python program to Check if a String is a Palindrome?

Solution:

2. mystr = 'naman'
mystr1 = mystr[::-1]
if mystr == mystr1:
print('mystr is a palindrome')
else:
print('mystr is not a palindrome')
Write a Python program to calculate the length of a string.

Using- a) Length function b) using any Loop


Solution:
a) str1 = "resource.com"
print(len(str1))
3.
b) using any Loop
str1 = "resource.com"
count = 0
for char in str1:
count += 1
print(count)
Write a Python program to get a string made of the first 2 and last 2 characters
of a given string. If the string length is less than 2, return the empty string
instead.

Solution:
4. def both_ends(s):
if len(s) < 2:
return ''
return s[:2] + s[-2:]

print(both_ends('resource')) # Output: 'rece'


print(both_ends('w')) # Output: ''
Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to '$', except the first char itself.
Solution:

5. def change_char(str1):
char = str1[0]
str1 = char + str1[1:].replace(char, '$')
return str1

print(change_char('restart')) # Output: 'resta$t'


Write a Python program to remove characters that have odd index values in a
given string.
Solution:
str1 = 'abcdef'
result = ''
6.
for i in range(len(str1)):
if i % 2 == 0:
result += str1[i]
print(result) # Output: 'ace'

Write a Python program to get a single string from two given strings, separated
by a space and swap the first two characters of each string.
Solution:
a = 'abc'
7. b = 'xyz'

new_a = b[:2] + a[2:]


new_b = a[:2] + b[2:]

print(new_a + ' ' + new_b) # Output: 'xyc abz'


Write a Python script that takes input from the user and displays that input
back in upper and lower cases.
Solution:
8. user_input = input("What's your favorite language? ")
print("My favorite language is", user_input.upper())
print("My favorite language is", user_input.lower())
Write a Python program to check whether a string starts with and end with
specified characters.
9. Solution :
string = "w3resource.com"
print(string.startswith("w3r")) # Output: True
print(string.endswith("com")) # Output: True
Write a Python program to format strings in different ways(min 2 way).
a) Input: Name-Shyam, Age - 30
Solution :
1) f-string method
name = "Shyam"
10. age = 30
formatted_text = f"My name is {name} and I am {age} years old."
print(formatted_text)

2) .format() method
text = "My name is {} and I am {} years old.".format(name, age)
print(text)
ZEAL EDUCATION SOCIETY’S
ZEAL COLLEGE OF ENGINEERING AND RESEARCH
NARHE │PUNE -41 │ INDIA

Record No.: ZCOER-ACAD/R/16M Revision: 00 Date:25/05/2025

Unit 4 Question Bank

Department: FY BTech Semester: II Academic Year: 2024-25


Class: FY Comp / IT / AI-DS / AI-ML Div. : A,B,C
Date: 25.05.2025
Course: Fundamental Python Programming
Q. Question
No.
Write a program to sort a list of integers in ascending order
Solution:
nums = [3, 1, 2]
1. nums.sort() # Sorts in ascending order
print(nums) # Output: [1, 2, 3]

Write a Python program to sum all the items in a list Using Loop.
Solution:
items = [1, 2, -8]
sum_numbers = 0
2.
for x in items:
sum_numbers += x
print(sum_numbers) # Output: -5

Write a Python program to get the largest number from a list Using Loop.
Solution:
list = [1, 2, -8, 0]
max_num = lst[0]
3.
for a in list:
if a > max_num:
max_num = a
print(max_num) # Output: 2
Write a Python program to get the 4th element from the last element of a
tuple.
Solution:
tuplex = ("w", 3, "m", "o", "u", "r", "a", "i")
4.
print(tuplex) # Prints the full tuple
print(tuplex[3]) # 4th element: 'o'
print(tuplex[-4]) # 4th from end: 'u'

Write a Python program to count the number of strings from a given list of
strings. The string length is 2 or more and the first and last characters are
the same.
Solution:
5. words = ['abc', 'xyz', 'aba', '1221']
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
print(ctr) # Output: 2

Write a Python program Using List Comprehension to print the numbers


of a specified list after removing even numbers from it.
6. Solution:
num = [7, 8, 120, 25, 44, 20, 27]
num = [x for x in num if x % 2 != 0]
print(num) # Output: [7, 25, 27]

Write a Python program to generate and print a list of the first and last 5
elements where the values are square numbers between 1 and 30 (both
included).
Solution:

7.
l = []
for i in range(1, 31):
l.append(i ** 2)

print("First 5 squares:", l[:5]) # Output: [1, 4, 9, 16, 25]


print("Last 5 squares:", l[-5:]) # Output: [676, 729, 784, 841, 900]
Write a Python function that takes two lists and returns True if they have
at least one common member. If no common member exists, return False.
Solution:

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

8. found_common = False
for x in list1:
if x in list2:
found_common = True
break

print(found_common) # Output: True

Write a Python program to check whether an element exists within a tuple.


Solution :
9.
tuplex = ("r", "e", "s", "o", "u", "r", "c", "e")
print("r" in tuplex) # Output: True
print(5 in tuplex) # Output: False

Difference between List and Tuple (min 5 points each point 1M)
Solution :
List Tuple
1. Lists are mutable (can Tuples are immutable (cannot be
be changed) changed)
2. Defined using square
Defined using parentheses ()
brackets []
10.
3. Faster than lists due to
Slower than tuples
immutability
4. Can be used for
Used for fixed data
dynamic data
5. Supports methods like
Does not support most list
.append(),
methods
.remove()
ZEAL EDUCATION SOCIETY’S
ZEAL COLLEGE OF ENGINEERING AND RESEARCH
NARHE │PUNE -41 │ INDIA

Record No.: ZCOER-ACAD/R/16M Revision: 00 Date:25/05/2025

Unit 5 Question Bank

Department: FY BTech Semester: II Academic Year: 2024-25


Class: FY Comp / IT / AI-DS / AI-ML Div. : A,B,C
Date: 25.05.2025
Course: Fundamental Python Programming
Q.
Question
No.
Write a Python program to check if a set is a subset of another set.

Solution:

setx = set(["apple", "mango"])


sety = set(["mango", "orange"])
setz = set(["mango"])

print("x:", setx)
print("y:", sety)
print("z:", setz, "\n")

print("If x is a subset of y")


1. print(setx <= sety)
print(setx.issubset(sety))

print("If y is a subset of x")


print(sety <= setx)
print(sety.issubset(setx))

print("\nIf y is a subset of z")


print(sety <= setz)
print(sety.issubset(setz))

print("If z is a subset of y")


print(setz <= sety)
print(setz.issubset(sety))

Write a program to find the common elements of two sets.


2.
Solution:
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])

print("Original set elements:")


print(setx)
print(sety)

print("\nIntersection of two sets:")


setz = setx & sety
print(setz) # Output: {'blue'}

Write a program to add the new elements of an existing set.

3. Solution:
set1 = {1, 2, 3}
set1.add(4) # Adds one item
print(set1) # Output: {1, 2, 3, 4}

Using set comprehension, how would you write a Python program to identify the
even numbers within the range of 1 to 10 (inclusive)?
4.
Solution:
even_numbers = {x for x in range(1, 11) if x % 2 == 0}
print(even_numbers) # Output: {2, 4, 6, 8, 10}

Write a Python program to add a key to a dictionary.

Solution:
5.
d = {0: 10, 1: 20}
print("Original dictionary:", d)
d.update({2: 30}) # Add new key-value pair
print("Updated dictionary:", d) # Output: {0: 10, 1: 20, 2: 30}

Write a Python script to generate and print a dictionary that contains a number
(between 1 to 10) in the form (x, x*x) by using dictionary comprehension.
6. Solution:

squares = {x: x ** 2 for x in range(1, 11)} # For numbers 1 to 10


print(squares)

Write a Python program to iterate over dictionaries using for loops.

7. Solution:

d = {'Red': 1, 'Green': 2, 'Blue': 3}


for key, value in d.items():
print(key, 'corresponds to', value)
Explain any five common methods used with Python dictionaries, providing a
clear example for each method to illustrate its functionality.

Solution:
my_dict = {
"name": "ABC",
"age": 25,
"city": "Pune"
}

print("Dictionary:", my_dict)

# a) keys()
8. print("Keys:", my_dict.keys())

# b) values()
print("Values:", my_dict.values())

# c) items()
print("Items:", my_dict.items())

# d) get()
print("Get 'name':", my_dict.get("name"))

# e) pop()
my_dict.pop("name")
print("After popping 'name':", my_dict)

Write a Python program to sum all the items in a dictionary.

9. Solution :
my_dict = {'data1': 100, 'data2': -54, 'data3': 247}
result = sum(my_dict.values())
print("Sum of all values:", result) # Output: 293
Difference between Set and Dictionary (min 5 points each point 1M)
Solution :

Set Dictionary
1. Unordered collection of unique Unordered collection of key-value
elements pairs
2. Elements are accessed directly Values are accessed using keys
10. 3. Defined using {1, 2, 3} Defined using {"a": 1, "b":
2}
4. No keys; only values Keys must be unique; values can
repeat
5. Used for membership tests, set Used for data mapping and lookups
operations
ZEAL EDUCATION SOCIETY’S
ZEAL COLLEGE OF ENGINEERING AND RESEARCH
NARHE │PUNE -41 │ INDIA

Record No.: ZCOER-ACAD/R/16M Revision: 00 Date:25/05/2025

Unit 6 Question Bank

Department: FY BTech Semester: II Academic Year: 2024-25


Class: FY Comp / IT / AI-DS / AI-ML Div. : A,B,C
Date: 25.05.2025
Course: Fundamental Python Programming
Q.
Question
No.
Define a function that calculates the factorial of a number and call it from the
main program.

Solution:

def factorial(n):
1. result = 1
for i in range(1, n + 1):
result *= i
return result

# Main Program
num = int(input("Enter a number: "))
print("Factorial is:", factorial(num))

Write a function that takes a list of numbers as input and returns the sum of all
elements.

Solution:

2. def sum_of_elements(numbers):
total = 0
for num in numbers:
total += num
return total

my_list = [1, 2, 3, 4, 5]
result = sum_of_elements(my_list)
print("Sum:", result)
Implement a lambda function to square a given number.

Solution:
3.
number = int(input("Enter a number: "))
square = lambda x: x**2
squared_number = square(number)
print(number, "-> Its square is:", squared_number)

Using python user defi ne function Write a program to print the even numbers
from a given list.

Solution:

def is_even_num(l):
4.
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum

print("Even numbers:", is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))

Use the math module to calculate the area of a circle given its radius.
Solution:

5. import math

r = int(input("Enter the radius of the circle: "))


area_c = math.pi * r * r
print("Area of the circle:", area_c)

Write a Python function which calculates the area of a rectangle, explain how
default arguments function within the code. Specifically, illustrate what
happens when the function is called with only one argument and when it's
called with two arguments, referencing the output produced in each case.
Solution:

def calculate_area(length, width=5):


6. area = length * width
print(f"Area of rectangle: {area}")

# Only length provided → width defaults to 5


calculate_area(10) # Output: 50

# Both length and width provided


calculate_area(10, 8) # Output: 80
📌 Explanation:
If one argument is missing, Python uses the default value defined (width=5). If both
are provided, it overrides the default.

Write a Python function which prints the provided name and course, illustrates
how keyword arguments are utilized in the subsequent function calls. Explain
how explicitly specifying the parameter names during the function call affects
the assignment of values to the name and course parameters, even when the
order of arguments in the function call differs from the function definition.
Solution:

def fun(name, course):


7. print("Name:", name)
print("Course:", course)

# Keyword arguments (order doesn’t matter)


fun(course="DSA", name="gfg")
fun(name="gfg", course="DSA")

📌 Explanation:
When using keyword arguments, the order doesn’t matter because the parameters are
explicitly named.

Write a Python function which prints the product name and its price, explain
how the order of arguments passed during the function call affects the output.
Illustrate this by comparing the output of "Case-1," where the arguments are
provided in the defined order, with the output of "Case-2," where the order is
reversed. What does this demonstrate about positional arguments in Python
functions?
Solution:

def productInfo(product, price):


print("Product:", product)
print("Price: $", price)
8.
# Case-1: Correct order
print("Case-1:")
productInfo("Laptop", 1200)

# Case-2: Incorrect order


print("\nCase-2:")
productInfo(1200, "Laptop")

📌 Explanation:
With positional arguments, the order matters. Reversing them will swap meanings.
Explain the concept of a Python function, including its syntax, the process of
calling or invoking it, and the purpose and usage of the return keyword with
illustrative examples?
Solution :

# Function definition
def add(a, b):
return a + b # 'return' sends back the result

# Function call
result = add(5, 3)
print("Sum:", result)
9.

📌 Explanation:

 Function: Block of code designed to perform a task.


 Syntax:

def function_name(parameters):
# code block
return value

 Calling: Just use function_name(args).


 return: Sends back output for use later.

What is the primary purpose of using modules and packages in Python?


Elaborate on the benefits they offer in terms of code organization,
reusability, and maintainability. Additionally, provide a brief overview of
standard library modules and their significance.
Solution :
📌 Modules:
A module is a .py file containing reusable code (functions, variables, classes).

📌 Packages:
A package is a directory containing multiple modules and a special __init__.py file.

🔍 Benefits:
10.
 Code Reusability: Write once, use multiple times.
 Modularity: Divide large code into smaller parts.
 Maintainability: Easier to debug and update.

🔧 Examples from Python Standard Library:

 math → Mathematical operations


 random → Random number generation
 datetime → Date and time manipulation
 os → Interact with operating system
 sys → System-specific parameters and functions

You might also like