简体   繁体   中英

Storing a multiple amounts of integers in a one variable, so i can sum them up or show all of them to a user

def adding_report(var):
    lists=[]
    total=0
    while True:
        if var.isdigit():
            total+=int(var)
            int(var).append(lists)
        elif var=="Q":
            choice=input("For total 'T' , for all 'A'").upper
            if choice=='T':
                print(total)
                break               
            elif choice=='A':
                print(lists)
                print(total)
                break                
            else:
                print("Invalid input")

while True:
    var=input("Enter an integer or Quit 'Q' ")
    if var.isdigit():
        adding_report(var)
    elif var=="Q":
        adding_report(var)
        break
    else:
        print("Invalid input")

I am trying to store the input that i got from the user. I need to store them in a one variable. I will show all the input when user wants it or i will sum up all of them and show the total result to a user. But i dont know how to store integers in a one variable.

The final list should be like this; input1 input2 input3

Total:input1+input2+input3

You already got a clean solution from @bhansa but, just in case you wanted to maintain the loop and sequential user inputs, as they were in your script:

def adding_report(var, values):
    if var.isdigit():
        values.append(int(var))
        return False
    elif var.lower() == 'q':
        total = sum(values)
        choice = input("For total: T , for all: A\n").lower()
        if choice in 'ta':
            if choice == 'a':
                print(' '.join([str(i) for i in values]))
            print(total)
            return True
        print("Invalid input")

if __name__ == "__main__":
    values = []
    total = 0
    while True:
        var = input("Enter an integer or Quit 'Q'\n")
        exit = adding_report(var, values)
        if exit:
            break

A quick note: you don't need a while loop in your adding_report function and you want to break the main loop, when the user types Q


EDIT :

I corrected the above code to work in Python 3 (my bad, I had missed that's the version tagged in the question; thank you @MarkTolonen for pointing that out).

To have the above code work with Python 2.7, one option is to replace input with raw_input ; otherwise, a fix can be added on top, while leaving the rest unchanged (as suggested here ):

try:
    # Fix Python 2.x
    input = raw_input
except NameError:
    pass

I'm no expert of multiple Python versions support, though, so there might be better solutions. Feel free to comment and/or expand, I'd be happy to hear.

If you just want to store inputs in a list and show total, Much simpler solution would be this:

lista = list(map(int, input().split()))

for index, item  in enumerate(lista):
  print("input{} : {}".format(index, item))

print("Total: ", sum(lista))

#  1 2 3 
# input0 : 1
# input1 : 2
# input2 : 3
# Total:  6

Put the above statements into functions according to your conditionals.

If your question is regarding the Edx Python course, your code can look like below:

When use 'A' as the argument to adding_report() gives results in printing of all of the input integers and the total. 'T' gives results in printing only the total.

def adding_report(report):
my_sum = 0
my_rep = report
elements = ['Items']
print('Input an integer to add to the total or "Q" to quit')
while True:
    element = input('Enter an integer or "Q" for quit: ')
    if element.isdigit():
        my_sum += int(element)
        elements.append(element)
    elif element.lower().startswith("q"):
        if my_rep == 'A':
            for el in elements:
                print(el)
            print('\nTotal\n', my_sum)
            break
        elif my_rep == 'T': 
            print('\nTotal\n', my_sum)
            break
    else:
        print('"' + element + '"', 'is invalid input')


adding_report('A')
adding_report('T')

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