Author: | Carlos Santos |
Learning Line: | Programming |
Course: | PR1: Introduction to Programming |
Week: | 4 |
Competencies: | Students will be able to effectively define and use variables, programming flow control. |
BoKS: | 3bK2, The student understands the principles of data related software like Python, R, Scala and/or Java and knows how to write (basic) scripts. |
Learning Goals: | Variables and Data Types In-code Comments |
Flow Control – If… Then.. Else…
Before we start with if statements, we have to understand a bit better how boolean expressions work.
Boolean Expressions
Boolean are a data structure which may only have two values known as True / False. They are important for controlling the path of instructions.
For example, check if a value is higher than 0.
a = -1 a > 0 False
There are other boolean operators, that allow you to create more complete expressions. For example, if you want to check if a value is between 0 and 1 (inclusive).
b = 0.4 b >= 0 and b <= 1 True
The operation and only returns True if both instances are True.
Now imagine, you want to check the opposite, check is a number is not between 0 and 1 (inclusive). You can’t write:
c = 2 c < 0 and c > 1 False
you have one of the other two boolean operators.
c = 2 c < 0 or c > 1 True
The operation or returns True if any of instances are True.
Alternatively you can take the first expression, and negate it
d = 2 not(d >= 0 and d <= 1) True
The operation not inverts the value of a boolean. Note that you may have to use parenthesis, to assure the correct order of operations, similar to the multiplication and addition.
d = 2 not d >= 0 and d <= 1 False
If statement
Until now all the instructions that you placed, are executed. If statements allow to conditional execute instructions sets.
n = 10 if n > 0: print("Positive result")
It also allows you to branch your code, and chain multiple instructions, even use alternative branches:
n = 10 if n > 0: print("Positive result") print("Yes!") else: print("Negative result") print("Oh, no...")
Note, that by using if statements you are creating a new scope, which follows the same rule set in the functions lecture. Please revise the scope section, if you don’t recall.
You can obviously combine this to create more complete functions, for example.
def maximum(a,b): """ Function that returns the highest number between a and b. """ if a > b: return a else: return b
if…elif…elif…elif…else
There are times that, it is relevant to chain multiple conditions, the elif works exactly like you would chain multiple if else if else statements
def filmRating(recommendedMinimumAge: int) result = "" if recommendedMinimumAge >= 18: result = "R18" elif recommendedMinimumAge >= 16: result = "R16" elif recommendedMinimumAge >= 12: result = "R12" elif recommendedMinimumAge >= 9: result = "R9" elif recommendedMinimumAge >= 6: result = "R6" else: result = "AL" return result filmRating(10) 'R9'