简体   繁体   中英

Python If statement with only an integer?

I was reading python code and I stumbled upon this little snippet of code here

if array[index] < 0:
   return -1
if not array[index]:
   continue

I mainly use java, and I struggle to understand the second statement, where I can only see an integer in the if statement. Can someone please explain to me what this means?!

I think the second conditional statement was there to check whether the array[index] element is not None (equivalent to java's null ) or not 0 .

In python, both not None and not 0 are True

The equivalent Java statement for the second conditional would be:

if(array[index]!=null || array[index]!=0){
   continue;
}

Well, I guess you are normalizing a function, well the second statement

if not array[index]:
    continue

means that if there are none items on that position of the array then continue looping over the array, same goes for this condition:

if array[index]:
   print("found")

Basically evaluates the condition there's an item = true.

I hope it helped you out.

In some languages like Python and Perl, 0 is false and anything else (sans None ) is true . So not 0 would be the same as not false which would be true . So here is the equivalent in Java.

Assume int[] array = {0};

if (array[index] != 0) {
   return -1
}
if (!(array[index] != 0)) // or better `(array[index] == 0)` 
   continue;
}
// at this point array[index] is > 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM