Reputation: 480
I have some functions that are behaving erratically:
pos = [' '] * 9;
def defense_ai():
#if statement
if pos.count('X') > 1:
#various other if statements
if statement:
#statement
a = 5;
#...
else:
return False;
pos[a] = 'O';
raw_input('Done!')
return True;
def offense_ai():
#statement that doesn't matter
pass;
def main():
defense_ai();
if not defense_ai():
offense_ai();
main();
My problem is, raw_input('Done')
is executing, but then offense_ai()
runs. This shouldn't happen because defense_ai
is supposed to return True
right after raw_input
is called. To check out what defense_ai()
returns, I added a raw_input()
just before the if not defense_ai()
statement.
raw_input(defense_ai());
The result of this is False
. The raw_input('Done!')
does appear, but it returns False after all.
Why is this happening?
Upvotes: 1
Views: 1262
Reputation: 9969
This looks like a suspect section of code:
defense_ai();
if not defense_ai():
offense_ai();
It seems like you've misunderstood, calling defense_ai()
on a line by itself doesn't do anything with the value it returns. You need to assign it to something in order to use the return value, like this:
defenseResult = defense_ai();
in which case that is likely what you'd want to use for your if
statement.
if not defenseResult:
offense_ai();
The thing is, calling defense_ai()
even in an if
statement, will cause the code of the function to be executed, so your code is running twice and creating confusion. However, you can use this instead to not bother assigning the return result, and call defense_ai
just once as part of the if
statement.
Like this:
def main():
if not defense_ai():
offense_ai();
Just remember that if you ever see ()
at the end of a variable name that means a function is being executed (or else you have syntax error)
Upvotes: 1