If Statements


By HyperNeutrino
Written 19 days ago

The if statement is used to run code based on whether or not a certain condition is met. The basic syntax of an if statement is this:

if condition:
    print("hi")

In this code block, "hi" will be printed if and only if condition is considered true. 0, empty strings, empty lists, None, and False are considered false. Everything else, including positive or negative numbers, strings with any characters (including whitespace), lists with elements, and True are considered true.

For example:

number = int(input()) # read a number from the user
if number < 0:
    print("Your number is negative!")
if number == 0:
    print("Your number is zero!")
if number > 0:
    print("Your number is positive!")

The elif statement is a combination of else and if. Essentially, it is only run if previous conditions were all false but this one is true. For example:

if number % 2 == 0:
    print("Your number is even!")
elif number % 3 == 0:
    print("Your number is divisible by 3!")

This will print "even" for numbers like 2, 4, 6, 8, 10, etc. It will print "divisible by 3" for numbers like 3, 9, 15, etc. However, it will not print "divisible by 3" for 6. This is because 6 is even, so the first condition will pass. Since the first condition passed, further conditions will not be considered.

The else statement is run if all other conditions were not met. Essentially, it is the "if all else fails, do this" case. For example:

if number > 0:
    print("Your number is positive!")
elif number < 0:
    print("Your number is negative!")
else:
    print("Your number is zero!")

This code works the same as the first example (for the if statement): outputs positive/negative/zero based on the provided number. If the first condition passes (number > 0), "positive" is output. If that condition does not pass but the second one does (number < 0; note that these are exclusive), "negative" is output. Finally, if neither condition passes, we can assume the number is equal to zero (the else case).