I'm fairly new to python (coding in general really), but I mostly grasp what's put in front of me. I'm trying to create an input that will only accept integers, so I put together the following function:
def askFor(request):
"""Program asks for input, continues to ask until an integer is given"""
num = ' '
while (isinstance(num, int) == False):
num = input(request)
else:
return num
it works fine when i enter a number, but anything else breaks it instead of looping it back. Am I missing an element, or am I just best off to go with
str(input('wargharble: '))
while not isinstance(num, int):is a little more Pythonic thanwhile (isinstance(num, int) == False):. :)input()runseval()on whatever the user types in (see the docs), so if it's not valid Python syntax for a constant or literal expression, like42,1+2, or"Bob", an exception will be raised which your program will need to catch. I suggest you instead usenum = int(raw_input(request))within atry/exceptclause because it doesn't useeval()and is therefore safer.