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.

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

thank you, it worked. I think i tried using this method before but put it somewhere wrong. Accepted answer.
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))

1 Comment

The OP is checking if a string can be converted to an number, not if an an existing object has a numeric type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.