If/else Statements in Python
Python has an if
keyword which executes this task. In Python, the if
keyword follows an expression, and the body of the if
statement is denoted by an indentation (4 spaces or a single tab). The body may contain one or several statements which need to be evaluated under that condition.
In general, we have the syntax as,
SNIPPET
1if expression:
2 statement
The program evaluates the expression and will execute the statement if and only if the expression evaluates to True
.
For the odd-even number example above, if statements in Python can be written as,
xxxxxxxxxx
let x = 5;
if (x % 2 === 0) {
console.log("x is even");
} else {
console.log("x is odd");
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment