Question

I am trying to write a small program from a book assignment, but I am having trouble with detecting if the user's input is a int/float (increment to the total) or string (return error). I tried using .isdigit() on the add_to_total variable but when I type in a float, it skips straight to the else code block. I have tried searching on the internet but can't find a clear answer. Here is my code:

total = 0
print("Welcome to the receipt program!")

while True:
    add_to_total = raw_input("Enter the value for the seat ['q' to quit]: ")
    if add_to_total == 'q':
        print("*****")
        print "Total: $%s" % total
        break
    if add_to_total.isdigit(): #Don't know how to detect if variable is int or float at the same time.
        add_to_total = float(add_to_total)
        total += add_to_total
    else:
        print "I'm sorry, but '%s' isn't valid. Please try again." % add_to_total

Any answer would be greatly appreciated.

Was it helpful?

Solution 2

Use exceptions to catch user inputs that can not be summed up. Switch from testing any user input, to just guard the mathematical operation to sum up receipts.

total = 0
print("Welcome to the receipt program!")

while True:
    add_to_total = raw_input("Enter the value for the seat ['q' to quit]: ")
    if add_to_total == 'q':
        break
    try:
        total += float(add_to_total)
    except ValueError:
        print "I'm sorry, but '%s' isn't valid. Please try again." % add_to_total
print("*****")
print "Total: $%s" % total

OTHER TIPS

You can always use the try... except approach:

try:
    add_to_total = float(add_to_total)
except ValueError:
    print "I'm sorry, but '%s' isn't valid. Please try again." % add_to_total
else:
    total += add_to_total

Remember: it's easier to ask forgiveness than permission

Very close to an old entry : How can I check if my python object is a number?. The answer is:

isinstance(x, (int, long, float, complex))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top