Python Conditional Statement

  • Read
  • Discuss

Python provides several ways to control the flow of a program using conditional statements. These statements allow you to execute different codes based on whether a specific condition is true or false.

The most basic conditional statement is the if statement. The if statement is used to check whether a particular condition is true and if it is, the code block associated with the if statement will be executed. Here is an example:

x = 5
if x > 0:
    print("x is positive")

The output of the above code will be following

x is positive

In the above example, the code block associated with the if statement will be executed, because the condition x > 0 is true.

You can also include an else block after an if statement to specify code that should be executed if the condition is false:

x = -5
if x > 0:
    print("x is positive")
else:
    print("x is not positive")

The output of the above code will be following

x is not positive

In the above example, the code block associated with the else statement will be executed, because the condition x > 0 is false.

ELIF in Python

Python also provides an elif statement, short for “else if”, which can be used to check for multiple conditions:

x = 0
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

The output of the above code will be following

In the above example, the code block associated with the “elif” statement will be executed, because the condition x == 0 is true.

Operators in IF Statement in Python

You can also use the and, or, and not operators to check multiple conditions simultaneously. Here’s an example that combines two conditions using the and operator:

x = 5
y = 6
if x > 0 and y > 0:
    print("x and y are both positive")

The output of the above code will be following

x and y are both positive

In the above example, the code block associated with the if statement will be executed, because the conditions x > 0 and y > 0 are both true.

indentation

It’s also important to note that the if and else block must be indented. The amount of indentation doesn’t matter as long as you are consistent in the same program; it should be the same. But it’s a convention to use 4 spaces indentation.

You can use if-elif-else statements and logical operators inside other statements, such as inside while or for loops, to make the program more robust.

Conditional statements are a powerful tool that allows you to control the flow of your program and make it more flexible and adaptable. With this knowledge, you can now write more complex programs that can make decisions based on user input or the program’s state.

Leave a Reply

Leave a Reply

Scroll to Top