简体   繁体   中英

Trying to outputting a math equation with for loop in python

So I have changeable sized list with integers in it like [2,5,6,9,1] and I am trying to create an addition formula with for loop:

z= 1
while z > 0:
    for i in range(len(list)):
        print(list[i],"+", end=" ")
    z = 0
    print("=",sum(list),end=" ")

This is what i am trying and output is:

2 + 5 + 6 + 9 + 1 + = 23

What should I do if I want to output n integers and n-1 plus signs between integers?

You may use str.join that accept an iterable of strings. You need to map each int to str then join them using the + and print the result

values = [2, 5, 6, 9, 1]
formula = " + ".join(map(str, values))
print(formula, "=", sum(values))  # 2 + 5 + 6 + 9 + 1 = 23

# Using f-strings
formula = f'{" + ".join(map(str, values))} = {sum(values)}'
print(formula)

Use join :

def printfn(alist):
    expr = " + ".join((map(str, alist)))
    sum_val = sum(alist)
    print("{} = {}".format(expr, sum_val))

a = [1,2,3]
printfn(a)
# 1 + 2 + 3 = 6

b = [1,2,3,4]
printfn(b)
# 1 + 2 + 3 + 4 = 10

If my understanding is correct you looking for something recognize the list changing...

This will print out the new sum if an item was added to you list.

Here i created an example:

import threading
import time
import random

LIST = []


def add_function():
    _old_len = 0
    while True:
        if len(LIST) >= 2 and len(LIST) > _old_len:
            addstring = " + ".join(map(str, LIST))
            print(addstring, "=", sum(LIST))
            _old_len = len(LIST)


def increase_function():
    while True:
        LIST.append(random.randint(1, 20))
        time.sleep(2)



if __name__ == "__main__":
    x = threading.Thread(target=add_function)
    y = threading.Thread(target=increase_function)
    x.start()
    y.start()
    y.join()
    x.join()

Another possibility is to use sep= parameter of print() function.

For example:

lst = [2,5,6,9,1]

print(*lst, sep=' + ', end=' ')
print('=', sum(lst))

Prints:

2 + 5 + 6 + 9 + 1 = 23

Make the for loop in range( len(list)-1 ) and add a print (list[len(list)-1]) before z=0

list = [2,5,6,9,1] 

z= 1
while z > 0:
    for i in range( len(list)-1 ):
         print(list[i],"+", end=" ")
    print (list[len(list)-1],end=" ")
    print("=",sum(list),end=" ")
    z = 0

You can use enumerate() , starting with an index of 1

>>> l= [2,5,6,9,1]
>>> s = ''
>>> sum_ = 0
>>> for i, v in enumerate(l, 1):
         if i == len(l):
             # If the current item is the length of the list then just append the number at this index, and the final sum
             s += str(v) + ' = ' + str(sum_)
         else:
             # means we are still looping add the number and the plus sign
             s += str(v)+' +
>>> print(s)
2 + 5 + 6 + 9 + 1 = 23 

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