Thedudxo
Thedudxo

Reputation: 591

if statement skipped/ignored

when i run this code, and food is something like -5, it seems to completely skip the if statement and move on to the next part of the function (i only have part of it below)

def change_location():
global food
global units
global SP
if food < 0: #problem seems to be here
        print '------------------------------------------------------'
        print 'not enougth food'
        main()

the concept is that if you have no food, you cant go to a new location. I wouldn't mind an alternative to this.

Upvotes: 0

Views: 130

Answers (2)

John La Rooy
John La Rooy

Reputation: 304473

Probably @ubuntu is correct. Here's some quick tips to debug this type of thing

Add a print statement

print food
if food < 0: #problem seems to be here

Problem is that -5 and "-5" get printed exactly the same. Adding a repr helps

print repr(food)
if food < 0: #problem seems to be here

Now you see that food is '-5' aha.

It's also a good idea to learn about the debugger

import pdb;pdb.set_trace()
if food < 0: #problem seems to be here

This will give you a (Pdb) prompt in the console. Type "food" and press enter

(Pdb) food
'-5'

Again, you can easily notice that food is a string. This is such a common mistake that those types of comparison are no longer allowed in Python3

Upvotes: 3

unutbu
unutbu

Reputation: 880897

Make sure that food is not a string, because in CPython2, '-5' < 0 is False:

>>> '-5' < 0
False

You can test if this is the problem in your code by placing an assert before the if statement:

assert not isinstance(food, basestring)
if food < 0:
    ...

If food is a string (or unicode), the program stop with an AssertionError when it reaches the assert statement.

If it does turn out that food is a string, you will need to track down the source of the problem. When you find where food is being defined as a string, you can convert that string into an int using the int function:

food = int(...)

Of course, you could even use int in the condition,

if int(food) < 0:

but if food is intended to be an int, then this would be a sloppy way to program.


From the CPython2 docs,

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

So, since the word 'float' comes before 'string' alphabetically, all floats are ordered less than any string.

In Python3, comparing objects of different type raises a TypeError, thus removing this pitfall.

Upvotes: 5

Related Questions