简体   繁体   中英

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

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

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

Store the range then iterate and sum at the end

r = range(2, 6)

for i in r:
    print(i, end=" ")

print(f"sum = {sum(r)}")

Store the range and format the string all on one line

r = range(2, 6)

print(f'{" ".join([str(i) for i in r])} sum = {sum(r)}')

Add to the string in the loop then print at the end

r = range(2, 6)

s = ""
for i in r:
    s += f"{i} "

print(f"{s}sum = {sum(r)}")

Aside from what Leo mentioned, you can also try to use f'{}' method to print. I find it more handy and intuitive.

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

Output:

2  3  4  5  sum=14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM