-4

I have a simple code:

def string_times(str, n):
  if n==0:
    return ""
  else:
    for i in range(n):
        return str
        i=i+1
      
print(string_times('Hi',2))

The expected output is HiHi but my output is HI. Why is this happening?

Jana M
  • 49
  • 7

2 Answers2

1

You can directly use like:

print("Hi"*2)

Output: HiHi

Akshay Jain
  • 790
  • 1
  • 7
  • 21
-1

I'd write the function like this:


def string_times(str_, n):
    if n != 0:
        for i in range(n):
            print(str_, end='')
    else:
        print(' ',end='')

I'd not use 'str' as my variable and print within the function.

Then you can call the function python string_times('Hi',2) and it will get you the result you want.

If you want each 'Hi' in a different row just remove the end param

ShayHa
  • 402
  • 1
  • 5
  • 16