In Python, the if statement is used for conditional execution. It enables the program to execute different code blocks based on certain conditions. The basic syntax for the if statement in Python is:
main.py107 chars5 lines
Here, condition is a boolean expression that evaluates to either True or False. If condition is True, then the code block under the if statement is executed. If condition is False, then the code block under the else statement is executed.
For example, let's say we want to check whether a number is even or odd:
main.py87 chars7 linesThis will output:
main.py9 chars2 lines
The % operator is used to perform modulus division, which returns the remainder of the division. If num % 2 equals zero, then it means num is even, and the code block under the if statement is executed. Otherwise, if num % 2 is not zero, it means num is odd, and the code block under the else statement is executed.
gistlibby LogSnag