if statements and conditions
Now I would like to introduce you to a very useful tool in programming – if
conditions!
They are widely used to check whether a statement is true or not. If the given statement is true, then some instructions for our code are followed.
I'll present this subject to you with some simple code that will tell us whether a number is positive, negative, or equal to 0. The code's very short, so I'll show you all of it at once:
a = 5
if a > 0:
print('a is greater than 0')
elif a == 0:
print('a is equal to 0')
else:
print('a is lower than 0')
In the first line, we introduce a new variable called a
and we give it a value of 5
. This is the variable whose value we are going to check.
In the next line we check if this variable is greater than 0
. We do this by using an if
condition. If a
is greater than 0
, then we follow the instructions written in the indented...