birkenspanner birkenspanner - 1 year ago 36
Python Question

If statement not continuing

This code won't continue after it checks if the variable x is an integer or not. It gives out a ValueError, if x is not an int. How do I make the program ignore this error? I've tried to invert the statement like so:

elif x is isinstance(x, int):

but then, if I give it an integer, it immediately jumps to the else statement.

from tkinter import *

root = Tk()



greetings = ["hello", "Hello", "greetings", "Greetings"]

def out(event):

x = ent.get()
if x in greetings:
lr.configure(text=x + ",\n is there\n anything\n I can do\n for you?")
elif x is isinstance(x, int):
if int(x) == 0:
lr.configure(text="This is 0")
elif int(x) % 2 == 0:
lr.configure(text="This is a even number")
elif int(x) % 2 != 0:
lr.configure(text="This is an odd number")
elif x is "":

ent = Entry(root)
ent.grid(row=0, column=0, sticky=NW)
lr = Label(root, text="Output")
lr.grid(row=0, column=2, columnspan=2)
btn = Button(root, text="Process")
btn.grid(row=0, column=1, sticky=NW)
btn.bind("<Button-1>", out)


Answer Source

I think you might be trying to see if a string is an integer. Instead of that if statement, I would just use a try/except block:

def is_int(x):
        x = int(x)
        return True
        return False

Put that in your code and use it instead of the call to isinstance. As it is now, even if x was an integer, right now you're asking if x is (True or False), which is always going to return False. But if x is a string that could be turned into an integer, then isinstance(x,int) is never going to return True even if x could be converted to an int.