if (condition) {
# block of code to be executed if the condition is true
}
Python supports the usual logical conditions from mathematics
Ifcondition evaluates to true, statement_1 is executed; otherwise,
statement_2 is executed. statement_1 and statement_2 can be any statement,
including further nested if statements.
You may also compound the statements using else if to have multiple conditions tested in sequence, as follows:
if (20 > 18) {
printf("20 is greater than 18");
}
In the case of multiple conditions only the first logical condition which
evaluates to true will be executed. To execute multiple statements, group
them within a block statement ({ ... }) . In general, it's good practice
to always use block statements, especially when nesting if statements:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
It is advisable to not use simple assignments in a conditional expression,
because the assignment can be confused with equality when glancing over
the code. For example, do not use the following code:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is
not true, so we go to the else condition and print to screen that "a is greater than b".
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a"