Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 2

42 bytes added, 13:09, 1 August 2017
PART 2 - Using IF/ELIF/ELSE Statements
#For the following examples, try changing the numbers in the variables to get different results.
#Create one or more new files for testing the following steps (you won't need to submit them).
#Let's perform an IF statement testing a condition of two variable values. In this case, if variable 'a' is greater than variable 'b', then print a message, if False, do nothing.<sourcelang="python">
a = 10
b = 15
print('a is greater than b')
</source>What happened? Let's now use an IF/ELSE statement.<br><br>
#Issue the following at the ipython3 shell:<sourcelang="python">
a = 10
b = 15
print('b is greater than a')
</source>What happened?<br><br>This is neat, but what if 'a' is equal to 'b'? In order to make this work, we would need to perform another test! The 'elif' statement allows us to string together multiple if statement. This new statement 'elif' means: IF the first condition is False, it will check the second condition under 'elif'. HOWEVER, if the first condition is True, it will run the code indented under the first condition and SKIP the 'elif' statement. Finally, we include the ELSE statement - in this case, if 'a' is equal to 'b' (i.e. fails first test since 'a' is not greater than 'b' and fails second test since 'a' is not less than 'b', so they must be equal to check other).<br><br>
#Modify your program to looks like this:<sourcelang="python">a = 10
b = 10
if a > b: