• Python Basics

  • Python Variables

  • Operators in Python

  • Conditional Statements in Python

  • Python Lists

  • Python Tuples

  • Python Sets

  • Python Dictionaries

  • Loops in Python

  • Python Arrays and Functions

  • Conclusion

Python If statements

Python Conditions and If statements

Conditional statements in Python are fundamental for making decisions in your code. They allow you to execute specific blocks of code based on certain conditions. This lesson will cover how to use if, elif, and else statements, as well as logical operators and other important concepts related to conditional statements.

Python Conditions

Python supports the following logical conditions:

  • 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

These conditions can be used in various ways, primarily in if statements and loops.

1. If Statement

An if statement allows you to test a condition and execute a block of code if the condition is true.

Syntax:

python
1if condition:
2    # code to execute if condition is true

Example:

python
1a = 33
2b = 200
3if b > a:
4    print("b is greater than a")

In this example, since b (200) is greater than a (33), the output will be:

Indentation

Python uses indentation (whitespace at the beginning of a line) to define code blocks. Proper indentation is crucial because Python does not use curly brackets like other languages.

Example (Incorrect Indentation):

python
1a = 33
2b = 200
3if b > a:
4print("b is greater than a")  # This will raise an IndentationError


Frequently Asked Questions