Salam, I'm given a user input that I have to sum it by itself n-times. Which means if the input is "5" for example, I should return 5 5 5 5 5 = 25
I used:
def sum(user_input):
inp_sum = 0
string = ''
for n in range(0, user_input, 1):
inp_sum = user_input
if n != user_input -1:
string = "5 "
else: string = '5'
return string ' = ' str(inp_sum)
but it returns
Failed for value=6
Expected: 6 6 6 6 6 6 = 36
Actual: 5 5 5 5 5 5 = 36
what is the solution?
CodePudding user response:
You hardcoded 5 in to the logic of your function, when you should be passing in the user input to the string format logic. Also, do not name your function sum as you will shadow the built-in function sum.
def mysum(user_input):
inp_sum = 0
string = ""
for n in range(0, user_input, 1):
inp_sum = user_input
if n != user_input - 1:
string = "{} ".format(user_input)
else:
string = str(user_input)
return "{} = {}".format(string, inp_sum)
CodePudding user response:
You can simplify it like this:
def user_input(n):
return "{} = {}".format(' '.join([str(n) for _ in range(n)]), str(n*n))
print(user_input(5))
# 5 5 5 5 5 = 25
print(user_input(6))
# 6 6 6 6 6 6 = 36
