Python – Conditional Statements

Decision making is required when we want to execute a code only if a certain condition is satisfied. if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

A program evaluates anexpression and will execute statement(s) only if the expression is True. If the expression is False, the statement(s) is not executed.

In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.

Python interprets non-zero values as TrueNone and 0 are interpreted as False.

if 1>10:
    print("greater than 10")
elif 1 > 5:
    print("greater than 5")
else:
    print("less than 5")

The and keyword is a logical operator, and is used to combine conditional statements

if 1>10 and 2 > 3:
    print("")
elif 1 > 5:
    print("")
else:
    print("less than 5")

The or keyword is a logical operator, and is used to combine conditional statements

if 1>10 or 2 > 3:
    print("")
elif 1 > 5:
    print("")
else:
    print("less than 5")

 

Pass statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

if 3 > 2:
  pass

 

Source on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *