简体   繁体   中英

How do I add numbers together using loops?

def adding():
    total = 0
    x = 0
    while x != 'done':
        x = int(raw_input('Number to be added: '))
        total = x + total
        if x == 'done':
            break
    print total

I cant figure out how to add numbers that a user is inputing, and then stop and print the total when they input 'done'

I'm assuming it's yelling at you with a ValueError when the user inputs "done" ? That's because you're trying to cast it as an int before checking if it's a number or the sentinel. Try this instead:

def unknownAmount():
    total = 0
    while True:
        try:
            total += int(raw_input("Number to be added: "))
        except ValueError:
            return total

Alternatively, you can change your own code to work by doing:

def unknownAmount():
    total = 0
    x = 0
    while x != "done":
        x = raw_input("Number to be added: ")
        if x == "done":
            continue
        else:
            total += int(x)
    return total

But beware that if the user enter "foobar" , it will still throw a ValueError and not return your total.

EDIT: To address your additional requirement from the comments:

def unknownAmount():
    total = 0
    while True:
        in_ = raw_input("Number to be added: ")
        if in_ == "done":
            return total
        else:
            try:
                total += int(in_)
            except ValueError:
                print "{} is not a valid number".format(in_)

This way you check for the only valid entry that's NOT a number first ( "done" ) then holler at the user if the cast to int fails.

There are many similar questions here, but what the hell. Simplest would be:

def adding():
    total = 0
    while True:
        answer = raw_input("Enter an integer: ")
        try:
            total += int(answer)
        except ValueError:
            if answer.strip() == 'done':
                break
            print "This is not an integer, try again."
            continue
    return total

summed = adding()
print summed

More fancy take on problem would be:

def numbers_from_input():
    while True:
        answer = raw_input("Enter an integer (nothing to stop): ")
        try:
            yield int(answer)
        except ValueError:
            if not answer.strip(): # if empty string entered
                break
            print "This is not an integer, try again."
            continue

print sum(numbers_from_input())

but here are some python features you may not know if you are begginer

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