Thursday, August 18, 2022

[FIXED] How to print a loop's result horizontally with a string in python?

Issue

I want to print a loop's result horizontally with a string and a variable.

My code

total = 0
for i in range(2, 6):
    total += i
    print(i, end=' ', 'sum = {}'.format(total))

The output I want:

2 3 4 5 sum=14

Solution

You need to put the print of the sum outside the loop

total = 0
for i in range(2, 6):
    total += i
    print(i, end=' ')
print('sum = {}'.format(total))

Output

2 3 4 5 sum = 14


Answered By - Leo Arad
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.