Home > database >  How to print the string by n times 'Hip' followed by 'Hurray!!!' using recursive
How to print the string by n times 'Hip' followed by 'Hurray!!!' using recursive

Time:02-22

The output should look like this Hip Hip Hip Hurray!!!

def cheers(n):
    
    if n == 0:
        print("Hurray!!!")
        
    elif n == 1:
        print('Hip'   ' '   'Hurray!!!')
        
    elif n > 1:
        cheers(n-1)
        print('Hip'   "Hurray!!!")

cheers(3)

CodePudding user response:

def hip_hip_hurray(n, message):
  if n == 0:
      print(message   'Hurray!')
  else:   
      hip_hip_hurray(n - 1, message   'Hip ')

hip_hip_hurray(3, '')
# prints: Hip Hip Hip Hurray!

The trick here is to use the message argument as an aggregator for the final output, with the stopping condition being used to add the Hurray suffix and print the message.

CodePudding user response:

if what you want is recursive solution Simply do this ... works !!

def cheers(n):
  if n<=0:
    print("Hurray!!!")
    return
  print("Hip",end=" ")
  cheers(n-1)

CodePudding user response:

Can't you just do that ?

def cheers(n):
    print('Hip ' * n   'Hurray!!!')
cheers(3) # Hip Hip Hip Hurray!!!

Using recursion:

def cheers(n):
    if n == 0:
        return 'Hurray!!!'
    return "Hip "   cheers(n - 1)

print(cheers(3))
# Hip Hip Hip Hurray!!!

CodePudding user response:

You can build the sentence by returning the relevant string instead of printing it

def cheers(n):
    if n == 0:
        return 'Hurray!!!'
    return f'Hip {cheers(n - 1)}'

print(cheers(3)) # Hip Hip Hip Hurray!!!
  • Related