Python

If Statements

YouTube

If statements in Python allow us to test certain conditions and execute certain blocks of code depending on whether the condition is true or false. These statements are a fundamental part of programming and are used extensively in almost all programming languages.

To create an if statement in Python, we start with the keyword if followed by the condition we want to test in parentheses. If the condition is true, the code block indented under the if statement will be executed. If the condition is false, the code block will be skipped and the program will continue to the next line of code.

If

Here is an example of an if statement in Python:

x = 10
if x > 5:
  print("x is greater than 5")

In this example, the condition is x > 5, which is true because x is equal to 10. Therefore, the code block print("x is greater than 5") will be executed and the message “x is greater than 5” will be printed to the console.

Else

We can also use an else statement to specify a code block to be executed if the condition in the if statement is false. For example:

x = 3
if x > 5:
  print("x is greater than 5")
else:
  print("x is not greater than 5")

In this example, the condition x > 5 is false because x is equal to 3. Therefore, the code block print("x is not greater than 5") will be executed and the message “x is not greater than 5” will be printed to the console.

Elif

We can also use an elif statement to specify additional conditions to test. For example:

x = 3
if x > 5:
  print("x is greater than 5")
elif x == 3:
  print("x is equal to 3")
else:
  print("x is not greater than 5 and not equal to 3")
Nested Ifs

We can also nest if statements inside of each other. This allows us to control the logic of the programme even further, by specifying a route for the code to take. A nested if would look something like this.

 

x = 5
if (x != 10):
    print("Not 10")
    x += 1
    if (x == 9):
        print("Will never reach 10!")
else:
    print("10 somehow reached...")

Whitespace is significant. The code blocks within an if statement must be indented using four spaces or one tab. This is to indicate that the code within the block is part of the if statement and should be executed if the condition is true. If the code is not indented correctly, it will not be considered part of the if statement and will be executed regardless of the condition.