If/Else Statement

The Python If Statement is used for decision making in coding.

If a condition is true, it runs the if part of the code, and if the condition is false, it runs the else part of the code.

Loops

If

The if statement is used to test whether a condition is true.

age = int(input("Enter your age: "))

if age < 18:
    print("hello kiddie")
Enter your age: 13
hello kiddie

In this code, the computer will ask for the person’s age. If the person is younger than 18, it’ll run the if part.

Elif

Elif is short of else and if. It’s when the previous condition isn’t true, but still applies to another condition.

age = int(input("Enter your age: "))

if age < 18:
    print("hello kiddie")
elif age == 18:
    print("just perfect")
Enter your age: 18
just perfect

In this code, Python runs the elif part if the person’s age is exactly 18. Not too old, not too young.

Else

The else part applies to anything that doesn’t fit the conditions above.

age = int(input("Enter your age: "))

if age < 18:
    print("hello kiddie")
elif age == 18:
    print("just perfect")
else:
    print("hello oldie")
Enter your age: 21
hello oldie

The person’s age is neither under 18 nor exactly 18, so it runs the else part.

Nested If Statements

It’s also possible to write nested If statements-

x = 40
print(x)

if x > 10:
    print("above ten,")
      if x > 20:
          print("and also above 20!")
      else:
          print("but not above 20.")
40
above ten,
and also above 20!

In this example, we have a number, x. It is already over 10, so the first if condition is true. Then, we are able to go into the other if/else statement, which checks if x is over 20. If it is, it runs the if part.

Misc

You can write an If loop without the elif

age = int(input("Enter your age: "))

if age < 18:
    print("hello kiddie")
else:
    print("hello oldie")
Enter your age: 18
hello oldie

We removed the elif part in this code. However, if the person’s age is 18, it still runs the else part. It’s because the if part only runs IF the person’s age is under 18, not exactly 18. So we need to be very specific when writing If loops.

Conclusion

That’s all! I hope you found this guide helpful.