117k views
4 votes
Will the Python code below print something? And will it terminate?

def print_n(s, n):
if n > 0:
print(s)
print_n(s, n-1)
return n
n = 3
while print_n("hi", n):
print_n("there!", n)
n = 0
a. no and no
b. yes and no
c. no and yes
d. yes and yes
e. syntax error

1 Answer

3 votes

Answer:

Yes and Yes

Step-by-step explanation:

When programs are written without indentation; it becomes a problem to read;

I'll rewrite your program as follows:

def print_n(s, n):

if n > 0:

print(s)

print_n(s, n-1)

return n

n = 3

while print_n("hi", n):

print_n("there!", n)

n = 0

Using the above as a point of reference,

Yes, the program will run and Yes, it'll terminate;

Because n is initialized to 3 at line 6 (where the main starts);

The following is passed to the function; s = "hi" and n=3

This prints "hi", three times

s = "there" and n=3 is then passed to the function print_n, afterwards;

The function then prints "there" three times

Then, the program terminates

User PRIYA PARASHAR
by
9.0k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.