1

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.

Himanshu
  • 4,327
  • 16
  • 31
  • 39
Thomas
  • 43
  • 1
  • 11

3 Answers3

5

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

Dunno
  • 3,632
  • 3
  • 28
  • 43
4

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
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • thank you, it worked. I think i tried using this method before but put it somewhere wrong. Accepted answer. – Thomas May 01 '14 at 11:27
4

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))
Community
  • 1
  • 1
user3585718
  • 396
  • 1
  • 4
  • The OP is checking if a string can be converted to an number, not if an an existing object has a numeric type. – chepner May 01 '14 at 11:31