'How to print the string by n times 'Hip' followed by 'Hurray!!!' using recursive function

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)


Solution 1:[1]

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.

Solution 2:[2]

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)

Solution 3:[3]

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!!!

Solution 4:[4]

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!!!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alon Gadot
Solution 2 gilf0yle
Solution 3
Solution 4 Guy