Mcq on loops in python
Q-1: What is the result of executing the following code? Q-2: What will the following code print? counter = 1 sum = 0 while counter <= 6: sum = sum + counter counter = counter + 2 print(sum) Q-3: What will be printed by the following code when it executes? sum = 0 values = [1,3,5,7] for number in values: sum = sum + number print(sum) Q-4: What is the last thing printed when the following code is run? number = 0 while number <= 10: print("Number: ", number) number = number + 1 Q-5: What does the following code print? output = "" x = -5 while x < 0: x = x + 1 output = output + str(x) + " " print(output) Q-6: What are the values of var1 and var2 that are printed when the following code executes? output = "" var1 = -2 var2 = 0 while var1 != 0: var1 = var1 + 1 var2 = var2 - 1 print("var1: " + str(var1) + " var2 " + str(var2)) Q-7: How many asterisks will be printed when the following code executes? for x in [0, 1, 2, 3]: for y in [0, 1, 2, 3, 4]: print('*') Q-8: The following code contains an infinite loop. Which is the best explanation for why the loop does not terminate? n = 10 answer = 1 while n > 0: answer = answer + n n = n + 1 print(answer)
Q-9: Which type of loop can be used to perform the following iteration: You choose a positive integer at random and then print the numbers from 1 up to and including the selected integer. Q-10: Which of the following statements won’t be printed when this Python code is run? for letter in 'Python': if letter == 'h': continue print('Current Letter : ' + letter) Q-11: What will the following code print? def mystery(str): out = "" for char in str: if char == "i": break if char == 'a': continue out += char return out print(mystery("walking")) Q-12: Which of the following will add up the numbers from 1 to 4? for i in range(1,4): sum = 0 sum = sum + i sum = 0 for i in range(1,4): sum = sum + i for i in range(1,5): sum = 0 sum = sum + i sum = 0 for i in range(1,5): sum = sum + sum sum = 0 for i in range(1,5): sum = sum + i Q-13: What will the following code print? def mystery(nums): out = [] for num in nums: if num < 0: continue else: out.append(num) return out print(mystery([3, -3, -2, 1])) Q-14: Which of the following will print five rows with five ‘*’ in each row? for i in range(0,5): print("*" * i) for i in range(0,5): print("*" * 5) for i range(1,5): print("*" * i) for i in range(1,5): print("*" * 5) Q-15: What will the following code print? for i in range(1,4): for j in range(1,4): print(i, j, end=' ') Q-16: What will the following code print? def mystery(nums): total = 0 for num in nums: if num == 999: break else: total += num return total mystery([8, 2, 999, 5, 4]) print(mystery("walking")) You have attempted of activities on this page |