Skip to main content

1. What are Conditionals?

  • Conditionals are used to make decisions in a program based on certain conditions.
  • They allow the program to execute specific blocks of code only if certain conditions are met.
  • Python uses if, elif, and else keywords for conditionals.

2. Types of Conditional Statements

1. if Statement

  • The if statement checks a condition. If the condition is True, the block of code under it is executed.
  • Syntax:
Example:

2. if-else Statement

  • The else block is executed if the if condition is False.
  • Syntax:
Example:

3. if-elif-else Statement

  • The elif (else-if) statement allows you to check multiple conditions.
  • The else block is executed if none of the if or elif conditions are True.
  • Syntax:
Example:

4. Nested Conditionals

  • You can nest if statements inside other if statements to check for more complex conditions.
  • Syntax:
Example:

3. Logical Operators in Conditionals

  • Logical operators (and, or, not) are used to combine multiple conditions.
  • and: Both conditions must be True.
  • or: At least one condition must be True.
  • not: Inverts the condition.
Examples:

4. Ternary Operator (Conditional Expression)

  • A shorthand way to write simple if-else statements in a single line.
  • Syntax:
Example:

5. Additional Examples

  • if Statement:
  • if-else Statement:
  • if-elif-else Statement:
  • Nested Conditionals:
  • Ternary Operator:

6. Best Practices

  • Use meaningful variable names to make conditions clear.
  • Avoid deeply nested conditionals to keep the code readable.
  • Use parentheses to group complex conditions for clarity.
  • Use comments to explain complex logic.
Example: