The if statement

The if statement

The if statement in Python is a conditional statement that allows you to execute different blocks of code depending on whether a certain condition is true or false. The syntax of the if statement is as follows:

sql

if condition:

    # code to be executed if the condition is true

If the condition is true, then the code inside the if block will be executed. If the condition is false, then the code inside the block will be skipped and the program will continue to the next statement.

The if statement can also be extended using the elif and else clauses. The elif clause allows you to check for multiple conditions, while the else clause allows you to execute code if none of the previous conditions were true. The syntax for using elif and else is as follows:

vbnet

if condition1:

    # code to be executed if condition1 is true

elif condition2:

    # code to be executed if condition2 is true and condition1 is false

else:

    # code to be executed if both condition1 and condition2 are false

It is important to note that the code inside the if block and its related elif and else blocks must be indented properly. The standard indentation in Python is four spaces.

Here is an example of using the if statement to check if a number is even or odd:

bash

x = 5

if x % 2 == 0:

    print(x, “is even”)

else:

    print(x, “is odd”) This will output “5 is odd” since the condition x % 2 == 0 is false for the value of x.

Share this post
[social_warfare]
Evaluation order and associativity
The while statement

Get industry recognized certification – Contact us

keyboard_arrow_up