PYTH0NP0WERED PYTH0NP0WERED - 8 months ago 31
Python Question

Hello, its the newb again about the end=' ' option

I do understand that this question has been asked many time and I have looked through the community for a clear answer to my question. I understand that (end=' ') is used to print everything on the same line. However I am trying print everything in that list on the same line after a string.

my code is:

def print_all_numbers(numbers):
for x in numbers:
print('Numbers: %d ' % (x,end=''))

Just wanted to find out if I am using this correctly? I have looked at other examples and I believe that it should work.


Your code is illegal as you trying to assign a value inside a tuple - (x, end=''), with this tuple being passed to the format operator %. What you probably meant is:

print('Numbers: %d ' % x, end='')

But this would print: Numbers: 1 Numbers: 2 Numbers 3 ..., which probably isn't what you meant.
Assuming you meant: Numbers: 1 2 3 ... then you need to move you base string outside the loop.

def print_all_numbers(numbers):
    print('Numbers: ', end='')
    for x in numbers:
        print(x, end='')

But there are better ways to doing this using join:

def print_all_numbers(numbers):
    print('Numbers:', ' '.join(str(x) for x in numbers))