Python Forum

Full Version: Help with isinstance command (very simple code)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey!

I'm creating a simple function. The point would be to quit the code if n_files//n_pts is not an integer, however I can't get the condition to work: now it just prints 'Done', no matter if the result is an integer. I tried adding == True after the if command, but that doesn't do anything, so if anyone could help me on this one, I'd greatly appreciate it!

 print('Checking that n_files divided by n_pts is an integer...') if isinstance(n_files//n_pts, int): print('Done!') else: print('Not an integer, check the number of files in your folder') quit()
EDIT: Problem solved by changing command to if n_files//n_pts == int and using sys.exit() to quit the process!
I'm pretty sure your problem is not solved. // is floor division, and the result is always an integer if the arguments are integers. If you want to know if n_files is evenly divisible by n_pts this should work:
if n_files % n_pts == 0: print('Done!')
Using sys.exit() to quit a process is usually a sign that you were too lazy to organize your code in a logical manner. When code is well organized you can get a feel for the flow just by looking at the white space. When code is sprinkled with "global" and "sys.exit()" you have to read the words.

For example:
def interesting_stuff() """Does all the interesting stuff""" if n_files % n_pts == 0: interesting_stuff() else: print('You messed up')
Oh, thanks! Seems that my solution only worked if I manually entered the number of files, but when I asked for the code to calculate the number of files in a folder it wouldn't work. I took out sys.exit() as well. Thank you!