Loading...

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
2 lines
|
14/ 500 tokens
1
2
if condition:
    # code to execute if condition is true
Code Tools

Example:

python
4 lines
|
15/ 500 tokens
1
2
3
4
a = 33
b = 200
if b > a:
    print("b is greater than a")
Code Tools

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
4 lines
|
23/ 500 tokens
1
2
3
4
a = 33
b = 200
if b > a:
print("b is greater than a")  # This will raise an IndentationError
Code Tools