From your code:
fstring+=fstring+string
This takes whatever fstring
already is, plus string
and adds that to fstring
.
So, fstring
goes from ''
to '' + '' + 'Hi'
which is 'Hi'
. And then to 'Hi' + 'Hi' + 'Hi'
and finally to 'HiHiHi' + 'HiHiHi' + 'Hi'
.
Also, you use for var in range(1,number+1):
, but it would be more readable and quicker to use for var in range(0, number):
, since you don’t really need the value of number
to range from 1
to number
, you just want it to run number
times.
You also don’t need var
, in that case you can use _
which tells Python to just ignore the actual loop variable name.
Instead of printing at the end, you probably want the function to return the result, so it can be used somewhere (for printing, for example).
Finally, I’d recommend against calling a variable string
, because this might get confused with the builtin str
. Something like s
is a common name for a temporary string.
So, you’d end up with:
def repeat(s, number):
result = ''
for _ in range(0, number):
result += s
return result
print(repeat("Hi", 3))
CLICK HERE to find out more related problems solutions.