I've got a for loop which iterates through three elements in a list: ["123", "456", "789"]. So, with the first iteration, it will perform a calculation on each digit within the first element, then add the digits back up. This repeats for the other two elements. The outputs are then converted into strings and outputted.
for x in digits:
if len(x) == 3:
result1 = int(x[0]) * 8 ** (3 - 1)
result2 = int(x[1]) * 8 ** (2 - 1)
result3 = int(x[2]) * 8 ** (1 - 1)
result = result1 result2 result
decimal = []
decimal.append(result)
string = " ".join(str(i) for i in decimal)
return string
Problem is, when outputting the results of the calculations, it outputs them on separate lines, but I need them to be on the same line.
For example:
- 123
- 456
- 789
I need them to be like this:
- 123 456 789
I've tried putting the results of the calculations into a list, which is then converted to a string and outputted, but no dice - it still returns the values on separate lines instead of one.
EDIT:
I know how to do this using the print function:
print(str(result), end=" ")
But need to use the return function. Is there any way to do this?
CodePudding user response:
you can append each variable on a list using a_list.append('variable')
and print it using ' '.join(a_list)
whenever needed.
CodePudding user response:
The problem is that you are creating the list and returning the result inside the for
instead of outside. You only make a single calculation and return.
def foo(digits):
results = []
for x in digits:
if len(x) == 3:
result1 = int(x[0]) * 8 ** (3 - 1)
result2 = int(x[1]) * 8 ** (2 - 1)
result3 = int(x[2]) * 8 ** (1 - 1)
results.append(result1 result2 result3)
return " ".join(str(i) for i in results)
A more minor issue, but for instance, 3-1 is always 2 (at least in Euclidean mathematics) and 8**2 is always 64, so no need to calculate those values.