FPP Unit 3 To 6 Question Answer
FPP Unit 3 To 6 Question Answer
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.
Solution:
4. def both_ends(s):
if len(s) < 2:
return ''
return s[:2] + s[-2:]
5. def change_char(str1):
char = str1[0]
str1 = char + str1[1:].replace(char, '$')
return str1
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'
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
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 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)
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
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
Solution:
print("x:", setx)
print("y:", sety)
print("z:", setz, "\n")
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}
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:
7. Solution:
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)
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
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
Use the math module to calculate the area of a circle given its radius.
Solution:
5. import math
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:
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:
📌 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:
📌 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:
def function_name(parameters):
# code block
return value
📌 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.