Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.5k views
in Blog Post by 48 54 94
edited by

In this post, we're gonna learn how to write the different types of IF Conditions in Python.

if conditions


Before we getting started, let's first know more about Conditions

What're Conditions?

  • Conditions are a decision-making statement.
  • Perform different actions depending on a boolean condition that may be true or false.

Conditions In Python

  • If statement: is used to specify a block of code to be executed, if a specified condition is true.
  • If - else statement: is used to specify a new condition to test, if the first condition is false then it will be redirected to the else part
  • ELIF Statement: The elif keyword in pythons is the way of saying "if the previous conditions were not true, then try this condition".

Python If Statement

  • Python if statement is the easiest way to have a decision.
  • Use the if statement to specify a block of Python code to be executed if a condition is True.
  • It must end with a colon (:)
  • (white space at the beginning of a line) to define the scope in the code

 syntax :

if condition  
  #block of code to be executed if the condition is True
example:

Python if condition

output :

b is greater than a

Python (If–else) Statement

  • It is used when you want to choose between two alternatives.
  • An if statement can be followed by an optional else statement, which executes when the first condition is FALSE.
  • (white space at the beginning of a line) to define the scope in the code of if and else

syntax 

if condition
  #block of code to be executed if the condition is True
else 
  # block of code to be executed if the condition is False

Example

if-else in python

Python Elif statement

  • The elif keyword in pythons is the way of saying "if the previous conditions were not true, then try this condition". 
  • Also, make sure that the white space at the beginning of a line is to define the scope in the code of if and Elif.

 syntax 

if condition
#block of code to be executed if the condition is True
Elif condition
# block of code to be executed if the condition is False
Elif condition
# block of code to be executed if the condition is False
.
.
.

Example

elif statement in python

Nested If Statement

you can place an (if statement / if..else statement / if..elif statement) inside another statement and this called "nested"

syntax

if condition:
if condition:
  statements
else:
  statements
else:
statements

Conclusion

In this post, we have learned how to write different Conditions in the Python programming language.

See Also


If you don’t ask, the answer is always NO!
...