Conditional Statements in Python

Posted by

Conditional statements in Python allow you to execute blocks of code only if a certain condition is True .

if Statement

The if statement is used to check a condition and execute a block of code if the condition is True .

You can also use the elif keyword to check additional conditions if the first condition is False .

You can use as many elif clauses as you need. If none of the conditions are True , you can use the else clause to specify code to be executed.

Here is an example of an if statement:

This will print “x is greater than 5” because the condition (x > 5) is True .

ternary operator in Python

The ternary operator is a shorthand way to write an if statement. It has the following syntax:

Here is examples of a ternary operator:

Example1

This will print “x is greater than 5” because the condition (x > 5) is True .

Example 2

This will print “x is even” because the condition (x % 2 == 0) is True .

bool() function

The bool() function is used to evaluate a value as a boolean. It returns True if the value is considered “truthy,” and False if it is considered “falsy.”

Here are some examples of values that are considered “truthy”:

  • True
  • Non-empty strings and lists
  • Non-zero numbers

Here are some examples of values that are considered “falsy”:

  • False
  • None
  • 0
  • Empty strings and lists

You can use the bool() function to test whether a value is “truthy” or “falsy” in a conditional statement.

Here is an example of using the bool() function:

This will print “x is truthy” because the value of x (10) is considered “truthy.”

Comparison Operators In Python

We use comparison operators to compare two values and determine if they are equal, unequal, greater than, less than, etc.

Here are some common comparison operators:

  • == : equal to
  • != : not equal to
  • > : greater than
  • < : less than
  • >= : greater than or equal to
  • <= : less than or equal to

Here are some examples of using comparison operators in Python:

This will print:

Logical Operators in Python

We use logical operators to combine multiple conditions.

Here are some common logical operators:

  • and : both conditions must be True
  • or : at least one condition must be True
  • not : negates a condition

Here are some examples of using logical operators in Python:

This will print:

Here, you have learned Conditional Statements(if, elif and else) in Python.

Leave a Reply

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