-5

I have encountered a weird problem with following Python (2.7.3) script. Sometimes when e.g. a = True and b = False the subsequent if-clause evaluates to False and the code inside it will not be run.

It always works the first time when either a, b or both are True but sometimes later it randombly fails.

Can anyone explain this behaviour and how to avoid it? Thank you.

while True:
    a = b = False
    a = func1()   # Returns True or False
    b = func2()   # Returns True or False

    print a       # Just for debugging..
    print b       # Just for debugging..

    if(a or b):
        print "Here we are.."
        func3()   # It may take hours until we return from here

    time.sleep(45)
user1534160
  • 23
  • 2
  • 6
  • 1
    The first line is irrelevant. It has no bearing on the script's execution. Please show an example where you think `a or b` returns a `True`(ish) value but your `if` statement isn't executed. – Tim Pietzcker Jan 21 '14 at 06:53
  • 1
    can you show us the traceback from the "randombly fails"? Do you have output printed where `a` and `b` are false? – mhlester Jan 21 '14 at 06:54
  • You have to give us code to **reproduce** what you are saying. If you don't, it would be difficult to help you. – Christian Tapia Jan 21 '14 at 06:56
  • It seems more likely that `a or b` is evaluating to `True` because one of them is, in fact, `True`. Can you prove this assertion wrong? In other words, I suggest that the problem lies in `func1()` or `func2()`. – mojo Jan 21 '14 at 06:56
  • 1
    The statement in your question title is literally impossible. If python evaluates the statement to false, then both variables have a value that is considered false in a boolean context. Every time you think the python interpreter is wrong, think again - it's probably you that's wrong instead. – l4mpi Jan 21 '14 at 07:00
  • Are you sure you remembered to return the values your functions were computing? A common newbie mistake is to forget to `return` something and then run into all sorts of errors due to the default `None` return value. – user2357112 Jan 21 '14 at 07:08

1 Answers1

2

It may have something to do with what value(s) Python thinks is/are "True". Sometimes these rules are not intuitive; you may need to check the documentation on the topic. To aid in debugging, perhaps you could try instead of

print a
print b

something like

print a
if a:
    print "a is True"
print b
if b:
    print "b is True"

This should at least confirm that what you this is True/False is*actually* True/False.

aldo
  • 2,927
  • 21
  • 36