How to find if the value contains characters

Viewed 39

Right now am planning to add items into the database. The item name, price and all are all entered by the users. How do I find if theres any alphabets when entering the price? i tried using .isnumber() but it seems to be reading my decimal point as a character as well.

while True:
        itemPrice = input("Please Enter Item Price: ")
        if str(itemPrice).isnumeric()  == False:
            print("Please enter a value!")
        else:
            print(itemPrice)
            break

For example, they allow if i enter 5 but not 5.5 and since this is item price it should have decimals.

3 Answers

You can catch exceptions,

while True:
    itemPrice = input("Please Enter Item Price: ")
    try:
        itemPrice = float(itemPrice)
        print(itemPrice)
        break
    except ValueError:
        print("Please enter a value!")

you can use try/except block

a = 3.5345
a=str(a)

try: #if it can be converted to a float, it's true
    float(a) 
    print(True)
except: # it it can't be converted to a float, it's false
    print(False)

You could try using a for loop to check:

def containsAlpha(x):
    if True in [char.isalpha() for char in x]:
        return True
    return False

while True:
    itemPrice = input("Please Enter Item Price: ")

    if containsAlpha(itemPrice):
        print("Please enter a value!")
    else:
        print(itemPrice)
        break
Related