2 Logic with if ... else
Logic¶
Now that we know about variable types like integer, float, string, etc. We can now start programming some logic into our code using if
statements.
The general form written in pseudo code (not Python) is like this:
if <something-is-true> then
do something
else
do something else
# We can start with a Boolean
myBoolean = True
if myBoolean:
print('yes, it is true! it is the way.')
yes, it is true! it is the way.
That if
statement could be read out loud like:
If the variable myBoolean is true then print 'it is true! it is the way'
This is a good example where Python code is easy to read and understand. You can almost speak the code out loud!!!
Boolean operators¶
Now we will use the boolean operator ==
in a if
statement. That is a double equal sign!
==
is very different from =
. The =
is used to assign a variable while the ==
is used to ask if two things are the same (e.g. are equal).
New concept. All if
statements can have an optional else
.
if 1 == 2:
print('1 equals 2!')
else:
print('sorry, 1 does not equal 2')
sorry, 1 does not equal 2
That code is saying:
If 1 equals 2 then print '1 equals 2!', otherwise print 'sorry, 1 does not equal 2'
# do that again using variables
a = 1
b = 2
if a == b:
print('a equals b!')
else:
print('sorry, a does not equal b')
sorry, a does not equal b
Finally an example where things are true!
a = 100
b = 100
if a == b:
print('a equals b!')
else:
print('sorry, a does not equal b')
a equals b!
Our boolean conditionals are not limited to equals with ==
, we also have the following boolean conditionals:
>
>=
<
<=
# here is an example
a = 10
b = 200
if a < b:
print('a is less than b')
# and again with an if .. else
a = 300
b = 12
if a < b:
print('a is less than b')
else:
print('sorry, a is not less than b', 'I got a:', a, 'and b:', b)
a is less than b sorry, a is not less than b I got a: 300 and b: 12
Tutorial¶
Rewite the above code using >
or >=
# add your code here (click thee play button in the top toolbar to run your code)
Conclusion¶
Logic operations like if .. else
are critical to all programming. It allows our code to make choices and perform differently in different situations.