0

So basically I am trying to check if the user entered the correct variable type. It should be an int or a float. If not then there should be a message box saying that input is incorrect or something along the lines.

Here is the code. This function is currently for testing purposes. I have another one, but it has a lot of nested conditions thus I want to see if this works:

def test(gameNames, gamePrices):
    gamePriceInput = priceText.get("1.0", END)
    
    if type(int(gamePriceInput)) == int or type(float(gamePriceInput)) == float:
        print("its a number")
    elif type(str(gamePriceInput))==str :
        print("not a number")

gameNames and gamePrices are a lists, they don't serve any purpose in this test function, just kept them so when I go back and forth between the test function and the proper one that I wouldn't need to remove the lists.

Using Python 3.7

  • 1
    Instead of using type, try using [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance) – 12944qwerty May 04 '21 at 12:45
  • Alternatively if the input is always a string, try `gamePriceInput.isdigit()`. – Peter May 04 '21 at 12:46
  • Also, what's going wrong? Any errors? Unintended output? – 12944qwerty May 04 '21 at 12:46
  • If the user inputs `aaa` your program will crash because it is trying to call `int("aaa")` which will raise an error. You can use a `try`/`except` to catch the error and work from there. – TheLizzard May 04 '21 at 13:04
  • Yeap, thanks a lot, the try except worked perfectly. Here is the code, perhaps it will help other people: def checkIfNumber(): gamePriceInput = priceText.get("1.0", END) try: parsed=float(gamePriceInput) if type(parsed)==float: return True except ValueError: return False – DuckMeat PigMeat May 04 '21 at 15:47

4 Answers4

1

You can perhaps use the try statement to do this, you can try converting the value into a float as even if its an integer, it will get converted to a float and from your problem you seem to consider numbers to include both floats and integers.

Incase an exception is thrown converting the value to a float, it means it is not a number then a similar test can be done in the except statement for string check.

Like so -:

def check_type(val) :
    try :
        float(val) # Tries to convert the value to a float.
        print('Value is a number!') # If an exception is not thrown the value is a number and the same is printed.
    except ValueError :
        print('Value is not a number!') # If an exception is thrown the same is caught and the value is not a number and the same is printed.
    return

Also as you pointed out if you wish to just limit the entry to numeric value then you should check out - Restricting the value in tkinter entry widget

typedecker
  • 1,351
  • 2
  • 13
  • 25
0

You can use re.fullmatch() to do this.

if re.fullmatch("^(?:\d+\.?\d+)|(?:\.\d+)|(?:\d+.)$", str(gamePriceInput)) is None: # None means it didn't match
    print("Not a number")
else:
    print("Its a number")

See the regex101 save I made to test the regex.

12944qwerty
  • 2,001
  • 1
  • 10
  • 30
0

I wrote this Tkinter mock up Tkinter Application, that checks if the "Price" is a number (int, float) or not, and displays a message accordingly, I have commented at some of the essential sections and variables, hope this helps.

from tkinter import *
global root, canvas, ef, is_int, is_float, error, box, price_type_is_number


# Setting Our variables that we will use later to None for the time being
is_int = None
is_float = None
error = None
box = None
price_type_is_number = None  # This is the final result, if it's a number, Float, int, or not.

# Setting up the Tk Window and Canvas
root = Tk()
canvas = Canvas(width=500, height=500)
canvas.pack()


# Functions

def submit():
    global root, canvas, ef, is_int, is_float, error, box, price_type_is_number
    price_type_is_number = None
    if not is_int and not is_float: # If it's not a float and not an int it displays an error
        try: # Just Tries to remove any previous instances of the box element, or error element to avoid lag and overlapping
            box.destroy()
            error.destroy()
        except:
            pass
        box = Label(bg="gray75", width=20, height=5)
        price_type_is_number = False  # You can use this value to get the definite status if the price is a number, float, int. But here it sets it to False
        error = Label(text="Price must be a number", fg="red", bg="gray75")
        canvas.create_window(165, 200, anchor="nw", window=box)
        canvas.create_window(165, 210, anchor="nw", window=error)
    elif is_int or is_float: # If it's a float, or int it displays the correct message
        try: # Just Tries to remove any previous instances of the box element, or error element to avoid lag and overlapping
            box.destroy()
            error.destroy()
        except:
            pass
        price_type_is_number = False  # You can use this value to get the definite status if the price is a number, float, int. But here it sets it to True
        box = Label(bg="gray75", width=20, height=5)
        error = Label(text="Price is a number", fg="green", bg="gray75")
        canvas.create_window(165, 200, anchor="nw", window=box)
        canvas.create_window(165, 210, anchor="nw", window=error)


def process():
    global root, canvas, ef, is_int, is_float
    try: # checks to see if it can convert the str into a float
        f_test = float(ef.get())
        is_float = True # If it can it sets it's float status to true
    except ValueError: # If it can't sets it's float status to false
        is_float = False
    try: # Checks to see if it can convert the str into an int
        int_test = int(ef.get())
        is_int = True # If it can sets the int status to true
    except ValueError: # if it can't sets it to false
        is_int = False
    submit() # Runs the submit command


# Widgets

efl = Label(text="Price") # Label For Entry Field
ef = Entry() # Entry Field
efb = Button(text="Enter", command=process)# Button to submit


# Adding Widgets to Canvas
canvas.create_window(165, 150, anchor="nw", window=ef)
canvas.create_window(165, 110, anchor="nw", window=efl)
canvas.create_window(315, 145, anchor="nw", window=efb)
mainloop()
TmGopnik
  • 111
  • 8
0

The best way to do so is:

def check_type(val) :
  try :
    float(val) 
    print('The value entered was a number.') 
  except ValueError :
    print('The value entered was a string.') 
  return

The program tries to convert to a number, but when if it fails, it detects that it is a string.

Dharman
  • 30,962
  • 25
  • 85
  • 135