What is the expected output of the following code?
def func(num):
res = ‘*’
for _ in range(num):
res += res
return res
for x in func(2):
print(x, end=”)
A . **
B. The code is erroneous.
C. *
D. ****
Answer: D
Explanation:
Topics: def return for
Try it yourself:
def func(num):
res = ‘*’
for _ in range(num):
res += res
return res
for x in func(2):
print(x, end=”) # ****
# print(x, end=’-‘) # *-*-*-*-
print()
print(func(2)) # ****
The for loop inside of the function will iterate twice.
Before the loop res has one star.
In the first iteration a second star is added.
res then has two stars.
In the second iteration two more stars are added to those two star and res will end up with four stars.
The for loop outside of the function will just iterate through the string and print every single star.
You could get that easier by just printing the whole return value.
Latest PCEP-30-01 Dumps Valid Version with 124 Q&As
Latest And Valid Q&A | Instant Download | Once Fail, Full Refund