If, Elif, Else

In Python, there is a really easy way to execute some code only if a certain condition is met, with an if-statement.

var_a = 2
var_b = 5

if var_a + var_b > 0:
	print("Total is positive")
elif var_a + var_b == 0:
	print("Total is 0")
else:
	print("Total is negative")

This code will check for the condition that var_a plus var_b is greater than 0. If it is the case, we print that the total is positive.

At the second statement, we use the elif statement, meaning : “else, if this condition is met, do that…”. Notice how to test for equality (and not assign a value), we do not use a single equal sign, but two. This is a simple thing to remember.

Finally, we use the else statement for any other case.

We could also have tested that the sum of both is greater or equal to 0.

var_a = 2
var_b = 5

if var_a + var_b >= 0:
	print("Total is greater or equal to 0")
else:
	print("Total is negative")

The “greater or equal” sign is simply a greater sign, followed by a equal sign.

If you found the article useful or see ways in which it could be improved, please leave a comment :)


Like it? Buy me a coffeeLike it? Buy me a coffee

Categories:

Updated:

Leave a comment