Python Function MCQ
1). What is the output of the following code?
def square(d):
a = {}
for key,value in d.items():
a[key] = value**2
return a
square({‘a’:4,’b’:3,’c’:12,’d’:6})
a) {‘a’: 16, ‘b’: 9, ‘c’: 144, ‘d’: 36}
b) {‘a’: 8, ‘b’: 6, ‘c’: 24, ‘d’: 12}
c) {‘a’: 2, ‘b’: 3, ‘c’: 4, ‘d’: 6}
d) {‘a’: 4, ‘b’: 3, ‘c’: 12, ‘d’: 6}
Correct answer is: a) {‘a’: 16, ‘b’: 9, ‘c’: 144, ‘d’: 36}
Explanation: The code defines a function `square` that takes a dictionary `d` as an argument. Inside the function, it initializes an empty dictionary `a`. Then, it iterates over the key-value pairs of the input dictionary using the `items()` method. For each key-value pair, it calculates the square of the value and assigns it as a value in the new dictionary `a`, with the same key as the original dictionary.
2). What is the output of the following code?
def prime(lower, upper):
print(“Prime numbers between”, lower, “and”, upper, “are:”)
for num in range(lower, upper + 1):
count = 0
for i in range(1, num + 1):
if num % i == 0:
count += 1
if count == 2:
print(i, end=” “)
prime(1, 100)
a) Prime numbers between 1 and 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
b) Prime numbers between 1 and 100 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
c) Prime numbers between 1 and 100 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
d) Prime numbers between 1 and 100 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Correct answer is: a) Prime numbers between 1 and 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Explanation: The function `prime()` takes two parameters, `lower` and `upper`, which represent the range of numbers to check for prime numbers. The function then iterates over each number in the range using a for loop, starting from `lower` and ending at `upper + 1`. Inside the loop, a variable `count` is initialized to 0. Another for loop iterates from 1 to the current number (`num`). Within this inner loop, the program checks if the current number (`num`) is divisible evenly by the current value of `i`. If it is, the `count` is incremented by 1. After the inner loop finishes, the program checks if the `count` is equal to 2. If it is, it means the number is only divisible by 1 and itself, indicating it is a prime number. In this code snippet, the function `prime(1, 100)` is called, which finds and prints all the prime numbers between 1 and 100.
3). What is the output of the following code?
def odd(lower, upper):
print(“Odd numbers between”, lower, “and”, upper, “are:”)
for num in range(lower, upper + 1):
if num % 2 != 0:
print(num, end=” “)
odd(1, 50)
a) Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
b) Odd numbers between 1 and 50 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
c) Odd numbers between 1 and 50 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
d) Odd numbers between 1 and 50 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Correct answer is: a) Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
Explanation: The function `odd` takes in two parameters, `lower` and `upper`, and prints the odd numbers between `lower` and `upper`. In this case, the function is called with `lower` equal to 1 and `upper` equal to 50. The for loop iterates over the range from 1 to 51 (upper + 1). For each number in the range, if the number is not divisible by 2 (i.e., it is an odd number), it is printed with a space at the end. Therefore, the output will be “Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49”.
4). What is the output of the following code?
def add(a, b):
total = a + b
return total
add(5, 15)
a) 5
b) 15
c) 20
d) None
Correct answer is: c) 20
Explanation: The function `add()` takes two parameters, `a` and `b`, and adds them together. In this case, `a` is 5 and `b` is 15. The function returns the sum of `a` and `b`, which is 20. When the `add(5, 15)` function call is executed, it returns the value 20.
5). What is the output of the following code?
def fruit(fname, fprice, quantity):
print(“Fruit name: “, fname)
print(“Fruit price: “, price)
print(“Fruit quantity in kg: “, quantity)
print(“Bill: “, fprice * quantity)
fruit(“Apple”, 100, 2)
a) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 200
b) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 100
c) Fruit name: Apple, Fruit price: 200, Fruit quantity in kg: 2, Bill: 400
d) Fruit name: Apple, Fruit price: 200, Fruit quantity in kg: 4, Bill: 800
Correct answer is: a) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 200
Explanation: The function `fruit` takes three parameters: `fname` (fruit name), `fprice` (fruit price), and `quantity` (fruit quantity in kg). It then prints the values of these parameters along with the calculated bill, which is the product of `fprice` and `quantity`.
6). What is the output of the following code?
def leap(a):
if (a % 100 != 0 or a % 400 == 0) and a % 4 == 0:
print(“The given year is leap year.”)
else:
print(“The given year is not leap year.”)
leap(2005)
a) The given year is leap year.
b) The given year is not leap year.
c) The code raises an error.
d) None of the above.
Correct answer is: b) The given year is not a leap year.
Explanation: In the code, the function `leap()` takes a year as input and checks if it is a leap year or not. The condition `(a % 100 != 0 or a % 400 == 0) and a % 4 == 0` is used to determine the leap year. For the given input of `2005`, the condition `(a % 100 != 0 or a % 400 == 0) and a % 4 == 0` evaluates to `(True or False) and False`, which simplifies to `True and False`. Since the logical AND operator requires both conditions to be True for the entire expression to be True, the code execution enters the `else` block and prints “The given year is not a leap year.”
7). What is the output of the following code?
def reverse():
num = n = 123
rev = 0
while n > 0:
r = n % 10
rev = (rev * 10) + r
n = n // 10
print(“Reverse number: “, rev)
reverse()
a) Reverse number: 123
b) Reverse number: 321
c) Reverse number: 312
d) Reverse number: 132
Correct answer is: b) Reverse number: 321
Explanation: The code defines a function `reverse()` that calculates the reverse of a given number. In this case, the initial value of `num` and `n` is 123. Inside the `while` loop, the remainder of `n` divided by 10 (`r`) is calculated. It is then added to the `rev` variable after multiplying it by 10 (shifting the existing digits to the left) to make space for the new digit. The updated `rev` becomes the new reversed number. The variable `n` is then divided by 10 to remove the rightmost digit. This process continues until `n` becomes 0, at which point the loop terminates. Finally, the reversed number is printed using the `print()` function, resulting in “Reverse number: 321” as the output.
8). What is the output of the following code?
def library(bname, came):
print(“Book name: “, bname)
print(“Borrowed by:”, cname)
library(“Harry Potter”, “Yash”)
a) Book name: Harry Potter
b) Harry Potter Yash
c) Book name: Harry potter Borrowed by: Yash
d) Book name: Harry Potter Borrowed by: Yash
Correct answer is: d) Book name: Harry Potter Borrowed by: Yash
Explanation: The function `library` takes two parameters `bname` and `cname`. When the function is called with the arguments “Harry Potter” and “Yash”, it prints “Book name: Harry Potter” and “Borrowed by: Yash” using the `print` function. Therefore, the output will be “Book name: Harry Potter Borrowed by: Yash”.
9). What is the output of the following code?
def binary(n1, n2):
result = bin(int(n1, 2) + int(n2, 2))
print(f”Addition of binary numbers {n1}, {n2}: “, result[2:]) binary(‘100010’, ‘101001’)
a) 1001011
b) 1000111
c) 10101011
d) 111011
Correct answer is: a) 1001011
Explanation: The given code defines a function binary(n1, n2) that takes two binary numbers represented as strings n1 and n2. It then performs binary addition on these two numbers.
10). What is the output of the following code?
def search():
str1 = “python programming”
str2 = “python”
count = 0
for word in str1.split(” “):
if word == str2:
count += 1
if count > 0:
print(f”{str2} is in {str1}”)
else:
print(f”{str2} is not in {str1}”)
search()
a) python is in python programming
b) python programming is in python
c) python is not in python programming
d) python programming is not in python
Correct answer is: a) python is in python programming
Explanation: The code defines a function named `search()`. Inside the function, the variable `str1` is assigned the value “python programming” and `str2` is assigned the value “python”. The variable `count` is initialized to 0. The code then splits `str1` into a list of words using the space character as the separator. It iterates over each word in the list and checks if it is equal to `str2`. If a match is found, `count` is incremented by 1. After the loop, the code checks if `count` is greater than 0. If it is, it means that `str2` was found in `str1`, and it prints “{str2} is in {str1}”. Otherwise, it prints “{str2} is not in {str1}”.
11). What is the output of the following code?
def length():
str1 = “sqatools in best for learning python”
l = str1.split(” “)
print(f”Length of the last word {l[-1]} in the string: “, len(l[-1]))
length()
a) Length of the last word “python” in the string: 6
b) Length of the last word “sqatools” in the string: 8
c) Length of the last word “learning” in the string: 8
d) Length of the last word “in” in the string: 2
Correct answer is: a) Length of the last word “python” in the string: 6
Explanation: The code defines a function `length()` that splits the string `str1` into a list of words using the space as the delimiter. The last word of the string, accessed using `l[-1]`, is “python”. The `len()` function is then used to calculate the length of this last word, which is 6 characters. Finally, the function prints the message “Length of the last word python in the string: ” followed by the length of the word. Thus, the output of the code is “Length of the last word python in the string: 6”.
12). What is the output of the following code?
def mobile_number():
num = 24568526
if len(str(num)) == 10:
print(“It is a valid phone number”)
else:
print(“It is not a valid phone number”)
mobile_number()
a) It is a valid phone number
b) It is not a valid phone number
c) Error: Invalid input format
d) None of the above
Correct answer is: b) It is not a valid phone number
Explanation: The code defines a function `mobile_number()` that assigns the value `24568526` to the variable `num`. The code then checks if the length of the string representation of `num` is equal to 10. In this case, the length of the string `”24568526″` is 8, which is not equal to 10. Therefore, the code prints “It is not a valid phone number”.
13). What is the output of the following code?
def to_number():
num = 2563
str1 = “”
for i in str(num):
if i == “1”:
str1 += “One”
elif i == “2”:
str1 += “Two”
elif i == “3”:
str1 += “Three”
elif i == “4”:
str1 += “Four”
elif i == “5”:
str1 += “Five”
elif i == “6”:
str1 += “Six”
elif i == “7”:
str1 += “Seven”
elif i == “8”:
str1 += “Eight”
elif i == “9”:
str1 += “Nine”
print(str1)
to_number()
a) “TwoFiveSixThree”
b) “TwoFiveSixThree”
c) “Two Five Six Three”
d) “2563”
Correct answer is: c) “Two Five Six Three”
Explanation: The function `to_number` converts the number 2563 into its string representation with words. It iterates over each digit in the string representation of the number using a for loop. Inside the loop, it checks each digit and appends the corresponding word to the variable `str1`.
14). What is the output of the following code?
import itertools
def permutations():
string = “ABC”
list1 = list(string)
permutations = list(itertools.permutations(list1))
return permutations
permutations()
a) [(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]
b) [‘ABC’, ‘ACB’, ‘BAC’, ‘BCA’, ‘CAB’, ‘CBA’]
c) [(‘A’, ‘A’, ‘A’), (‘B’, ‘B’, ‘B’), (‘C’, ‘C’, ‘C’)]
d) [‘A’, ‘B’, ‘C’]
Correct answer is: a) [(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]
Explanation: The code uses the `itertools.permutations()` function to generate all possible permutations of the characters in the string “ABC”. The function returns a list of tuples, where each tuple represents a different permutation. In this case, the output will be `[(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]`, representing all the possible permutations of the characters ‘A’, ‘B’, and ‘C’.
15). What is the output of the following code?
def login():
name = “Ketan”
password = “password1234”
print(“Credential accepted”)
login()
a) Credential accepted
b) Ketan
c) password1234
d) None
Correct answer is: a) Credential accepted
Explanation: When the function `login()` is called, it assigns the string “Ketan” to the variable `name` and the string “password1234” to the variable `password`. The `print()` function is then used to output the message “Credential accepted” to the console. Therefore, the output of the code snippet will be “Credential accepted”.
16). What is the output of the following code?
def fun(string):
a = {}
l = string.split(” “)
for word in l:
a[word[0] + word[-1]] = word
return a
result = fun(“Python is easy li Learn”)
print(result)
a) {‘Pi’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘Li’: ‘Learn’}
b) {‘Pn’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘li’: ‘li’, ‘Ln’: ‘Learn’}
c) {‘Ph’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘Le’: ‘Learn’}
d) {‘Py’: ‘Python’, ‘is’: ‘is’, ‘ea’: ‘easy’, ‘Le’: ‘Learn’}
Correct answer is: b) {‘Pn’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘li’: ‘li’, ‘Ln’: ‘Learn’}
Explanation: The function fun takes a string as input and splits it into a list of words using the space as a delimiter. It then iterates over each word in the list. For each word, it creates a dictionary entry where the key is the concatenation of the first character and the last character of the word, and the value is the word itself. Finally, it returns the resulting dictionary.
17). What is the output of the following code?
def hcf(num1,num2):
if num1 > num2:
smaller = num2
else:
smaller = num1
for i in range(1, smaller+1):
if((num1 % i == 0) and (num2 % i == 0)):
hcf = i
print(f”H.C.F of {num1} and {num2}: {hcf}”)
num1 = 24
num2 = 54
hcf(num1,num2)
a) H.C.F of 24 and 54: 6
b) H.C.F of 24 and 54: 12
c) H.C.F of 24 and 54: 24
d) H.C.F of 24 and 54: 54
Correct answer is: a) H.C.F of 24 and 54: 6
Explanation: The given code calculates the highest common factor (H.C.F) of `num1` and `num2` using the Euclidean algorithm. In this case, `num1` is 24 and `num2` is 54. The code starts by assigning the smaller value (`num1` or `num2`) to the variable `smaller`. Then, it iterates from 1 to `smaller` using a for loop. For each iteration, it checks if both `num1` and `num2` are divisible by the current number `i`. If they are, the current number `i` is assigned to the variable `hcf`. Finally, it prints the calculated H.C.F using the f-string format. In this scenario, the H.C.F of 24 and 54 is 6. Therefore, the output of the code will be “H.C.F of 24 and 54: 6”.
18). What is the output of the following code?
def average(numbers):
total = sum(numbers)
average = total / len(numbers)
return average
scores = [90, 85, 92, 88, 95]
result = average(scores)
print(result)
a) 88
b) 90
c) 92
d) 95
Correct answer is: a) 88
Explanation: The code defines a function find_average that calculates the average of a list of numbers. It calculates the sum of the numbers using the sum() function and divides it by the length of the list. In this case, the average of the scores list [90, 85, 92, 88, 95] is 88. Therefore, the output will be 88.
19). What is the output of the following code?
def product(a, b=2):
return a * b
result1 = product(5)
result2 = product(5, 3)
print(result1, result2)
a) 10 15
b) 5 15
c) 10 6
d) 5 6
Correct answer is: a) 10 15
Explanation: The function calculate_product takes two parameters, a and b, with a default value of 2 for b. If the b argument is not provided, it uses the default value. In this case, result1 is calculated as 5 * 2, which is 10, and result2 is calculated as 5 * 3, which is 15. Therefore, the output will be “10 15”.
20). What is the output of the following code?
def power(base, exponent):
return base ** exponent
result = power(2, 3)
print(result)
a) 6
b) 8
c) 16
d) 23
Correct answer is: c) 16
Explanation: The function calculate_power calculates the result of raising the base to the exponent using the exponentiation operator **. In this case, 2 raised to the power of 3 is 8. Therefore, the output will be 8.