User Tools

Site Tools


products:ict:python:conditional_statements_if_elif_else

In Python, conditional statements are used to execute different blocks of code based on whether a certain condition evaluates to `True` or `False`. The basic structure includes `if`, `elif` (short for “else if”), and `else`.

Here's a basic syntax example:

x = 10

if x > 10:

  print("x is greater than 10")

elif x == 10:

  print("x is equal to 10")

else:

  print("x is less than 10")

In this example:

- The `if` statement checks if `x` is greater than 10. If it's true, it executes the corresponding block of code. - The `elif` statement checks if `x` is equal to 10. If the previous condition (`x > 10`) was false and this condition is true, it executes the corresponding block of code. - The `else` statement catches anything that didn't satisfy the previous conditions and executes its corresponding block of code. It doesn't have a condition because it's the “catch-all” block.

You can have multiple `elif` statements, and `else` is optional.

Here's another example with multiple conditions:

x = 5

if x > 10:

  print("x is greater than 10")

elif x == 10:

  print("x is equal to 10")

elif x > 5:

  print("x is greater than 5")

else:

  print("x is 5 or less")

In this case, since `x` is less than 10, it moves to the next condition and checks if `x` is equal to 10. Since it's not, it moves to the next condition and checks if `x` is greater than 5, which is false. Therefore, the `else` block is executed.

products/ict/python/conditional_statements_if_elif_else.txt · Last modified: 2024/03/01 19:15 by wikiadmin