Python if Statement

Summary: in this tutorial, you will learn how to use Python if statement to execute a block of code based on specified condition.

Simple Python if statement

You use the if statement to execute a block of code based on a specified condition. The syntax of the if statement is as follows:

The body code block only executes if the condition evaluates to true. If the condition evaluates to false, the code-block does not execute and control is passed the next statement followed the  if statement in the program.

Let’s take a look at an example of using the if statement.

Python if else statement

You use the if else statement to execute a code block in the if branch when the condition evaluates to true, and execute an alternative code block in the else branch when the condition evaluates to false.

The syntax of Python if else statement is as follows:

The following example shows you how to use the  if else statement:

Python if elif else statement

Sometimes, you want to execute the corresponding code block if a respective condition evaluates to true. In this case, you need to use Python if elif else statement.

The typical syntax of if elif else statement is as follows:

How it works.

  • If the  if-condition evaluates to true, the  if-code-block executes.
  • If any condition from  condition-1 to  condition-n evaluates to true, the corresponding code-block-i executes.
  • If no condition evaluates to true, the  code-block-else executes.

Let’s take a look at an example of using if elif else statement:

Notice that the ifif else and  if else if statement can be nested.

In this tutorial, you have learned how to use various forms of the Python if statement to execute a code block conditionally.

  • Was this tutorial helpful ?
  • YesNo