Guide to the Godot game engine/If statements
An "if" statement is a powerful piece of code. Every programming language has some kind of "if" statement. Valid examples are:
- "if" statement
var variable = 5 if variable == 5: pass # True if variable < 6: pass # True if (variable != {{Gdscript/string|5}) == ({{Gdscript/keyword|not} variable == {{Gdscript/string|5}): pass # True (both values are false, and false == false) if variable is int: pass # True if range({{Gdscript/string|5}) in variable: pass # [0,1,2,3,4] is not in 5. print("variable is 5" if variable == 5 else "variable is not 5")
Other rules to follow:
You must use indentation for a new line. You may put a statement on the same line as "if", but only if it is one line long: if variable == 5:print("variable is 5")
.
You cannot use "else if" syntax, like can be used in JavaScript, instead use the "elif" keyword.
A "value1 if something else value2" is a fast way to change a single argument in a function based on another value. It could be used like this: print("I am "+(age+" years old.") if age > 1 else "not at school.")
Otherwise, an "if" statement must have indented code after it. Even if it is just pass
.
Conditions in brackets are checked first, making if draw_lines_inverted == ((5 == 5) == (3 != 4)):
valid. If you do not use brackets, it reads the conditions left to right. So to check if value
is a bool, then check if it is true (without risking an error if it is not a bool) use if value is bool and value == true:
. If it is not a bool, the value is not checked to see if it is true.
See also: if conditions.