Printing extra comma in while loop - Python

Viewed 176

I don't want to print the last comma in my loop.

countWhile = 5
while countWhile > 0:
    if countWhile == 0:
        break
    else:
        print(countWhile, end=', ')
    countWhile -= 1
print("While Loop Finished.")

Actual result: 5, 4, 3, 2, 1,

Expected result: 5, 4, 3, 2, 1

1 Answers

This is one possible solution:

countWhile = 5
myList = []
while countWhile > 0:
    if countWhile == 0:
        break
    else:
        myList.append(str(countWhile))
    countWhile -= 1
print(', '.join(myList))
print("While Loop Finished.")

I can try to look for another simpler one if you want.

Related