简体   繁体   中英

How do I add multiple numbers from input in python, using the while statement. (or any other statement)

Input an integer to add to the total or "Q" to quit Enter an integer or "Q": 3 Enter an integer or "Q": 6 Enter an integer or "Q": 24 Enter an integer or "Q": 17 Enter an integer or "Q": 61 Enter an integer or "Q": nine nine is invalid input Enter an integer or "Q": q

Items 3 6 24 17 61

Total 111

This was the example that was given. Thanks

This is not a code writing service, and you should attempt it your first go, and then show us what you've tried. That being said, This should do it... Prints you beginning input line, and then add to totals from int, rejects other input except q and Q. Then it will return your final int

def add_to_total():
    print('Input an integer to add to the total or "Q" to quit')
    total=0
    while(True):
        newNum = input('Enter an integer or "Q": ')
        if(newNum=='q' or newNum=='Q'):
            return total
        try:
            total+=int(newNum)
        except:
            print('{} is invalid input'.format(newNum))

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