# Flow control in python :::info This is a revamp of this note done for the previous syllabus of IB. https://hackmd.io/@dprieto/flow-control ::: Flow control refers to the tools that we have to make some code to be executed and some that we don't to execute with some conditions. We can also see it as "valves" that regulate what happens and what doesn't. ![vag-know-regelventile-control_valves](https://hackmd.io/_uploads/rykhyPWkyg.jpg) _([source](https://www.vag-group.com/en/did-you-know/what-is-the-best-installation-position-for-pilot-operated-control-valves))_ This is mostly common as the **if** statements and their colleagues. There are several ways to write the same thing in different programming languages but the syntax is very similar. For the Minecraft players this is also like the levers that you may find there ![image](https://hackmd.io/_uploads/SJVUhZK2el.png) _([source](https://minecraft-archive.fandom.com/wiki/Lever?file=Lever.png))_ ## if statement The if statement has 2 main parts. * The condition (something that has to be resolve to either true or false) * The statement that's going to be executed in case that the condition is actually true. ### The condition A condition in an if (or elsewhere) needs to be something that it's either true or false. We can achieve it with either a **boolean variable** or **an expression** that returns a boolean #### Using a boolean A Boolean is a variable whose value can be either true or false. For example ```python= x = True if x: print("OwO") #"OwO" is outputç ``` :::info In this case we know that `x` is true but we can have some other part of the code that changes its value. ::: #### Using an expression We can use a comparator expresion this is an expresion that _resolves_ into something that is true or false. ```python= x = 5 if x > 3: print("OwO") #"OwO" is output ``` ![image](https://hackmd.io/_uploads/Hy9E3fYhex.png) _[(source)](https://www.w3schools.com/python/gloss_python_comparison_operators.asp)_ :::warning **Why 2 equals?** Because programming languages need to be unambiguous so each thing that you write can have only ONE meaning. And the meaning of one equal is **assignation** and the meaning of the 2 equals is **comparasion**. ::: :::success **Python understands several comparasions at the same time** So Python understands this code: ```python= x = 3 if 0<=x<=3: print("x is between 0 and 3") ``` But be aware that in many programming languages we would need to decompose this condition into 2 parts like this: ```python= x = 3 if 0<=x and x<=3: print("x is between 0 and 3") ``` Just FYI More info in the documentation: https://docs.python.org/3/library/stdtypes.html#comparisons :::danger Nevertheless, this doesn't compile: ```python age = 8 if age <= 12 and >=3: print("child") ``` It will tell you that the `>=` doesn't have anything to compare with. ![image](https://hackmd.io/_uploads/ryKooiOCel.png) ::: ::: #### Extra info We can also use a function that returns a boolean. ```python= def isPotato(): #do very complicated calculations return True if isPotato(): print("isPotato returns True") #"isPotato returns True" is output ``` **Truthies and falsies** in python You can run this code: ```python= x = 5 if x: print("OwO") #"OwO" is output ``` But if you run this one ```python= x = 0 if x: print("OwO") #nothing is output ``` This is because any data can be asked to be a boolean. And in some conditions, python is going to understand it as False(falsy) and others as a True (truthy). I suggest to avoid this unless you know what you're doing, but you may see it. Here you have more reference about it from the Python documentation ![image](https://hackmd.io/_uploads/S1cPGXthll.png) https://docs.python.org/3/library/stdtypes.html#truth-value-testing More info about it: {%preview https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/ %} ### The statement The statement is just code that is executed in case the if happens. It's important that many programming languages have different ways to confine this part and make it distinct from the rest of the code. In python to be precise, we need write `:` and then, in the next line, we have to use **identation**. When we finish the if we go back to the original identation (number of spaces before the instruction) Better shown than explained: The following code prints 3 lines ```python= if True: print("inside the if") print("2nd inside the if") print("outside the if") ``` The following code prints 1 line (the last one) ```python= if False: print("inside the if") print("2nd inside the if") print("outside the if") ``` :::warning :warning: Remember that identation needs to be _consistent_ :warning: This code for example is not going to be executed ```python= if True: print("inside the if") print("2nd inside the if") print("outside the if") ``` ...because in line 3 has an extra identation. This is the error: ![image](https://hackmd.io/_uploads/HyHSRXtnel.png) ::: ## Else The else statement will be executed **only if the condition is not met**. It's a short hand to write if the opposite of the previous if doesn't happen. It's written after the statement of the if (What happens if the if condition is met) Example ```python= n=2 if n<2: print("OwO") else: print("UwU") print("potato") #this prints UwU and potato ``` In python we need to write also the `:` after the else and use identation in a similar way to the if. ## Else if (elif) We can have and if statement that will not be met and then and else if will be executed only when a second condition is met. ```python= n=2 if n<2: print("OwO") elif n==0: print("UwU") print("potato") #this prints just potato ``` ## Combination of elifs and else We can combine different elif and else to set our different branches. Let's see an example ```python=! #weekDay, goingOutWithFamily and groceriesNeeded are previously defined print("Wake up") if weekDay: print("Go to school") elif goingOutWithFamily: print("Go out with the family") elif groceriesNeeded: print("Go to get some groceries") else: print("Stay at home") print("Have a good day") ``` Once we "hit" some condition that is the one that is going to be executed. And, of course "wake up" and "have a good day" is going to be printed in any case since they are outside the scope of the if. I'm going to do a Truth table with the possible combinations and outcomes from inside the if | weekDay | goingOutWithFamily | groceriesNeeded | output | | -------- | -------- | -------- | -------- | | False | False | False | Stay at home | | False | False | True | Get groceries| | False | True | False | Go out| | False | True | True | Go out | | True | False | False | Go to school| | True | False | True | Go to school| | True | True | False |Go to school | | True | True | True |Go to school | There can be many elifs but it can be only one else and needs to be at the end. (It would be a syntax error) ### Other example Construct a code in python that given an age stored in the variable age prints the following: In the case that is below 3 the program will output “Toddler”. If the age is between 3 (included) and 12 (included), the program will output “Child”. If the age is between 13 and 19 (both included), the program will output “Teenager”. In other cases, the program will not print anything. [4] ```python!= # we don't need to assign any value to age since already have it if age < 3: print("Toddler") elif age < 12: print("Child") elif age < 20: print("Teenager") ``` ```python!= # we don't need to assign any value to age since already have it if age < 3: print("Toddler") if 3<= age < 12: print("Child") if 12 <= age <= 19: print("Teenager") ``` ## Match (switch case) When we have many possibilities like asigning letters to morse functions or months from numbers we could concatenate if with a lot of elif, but many programming languages have something called "switch case". Python has added "match" for this purposes. You can find more info here. https://www.w3schools.com/python/python_match.asp ## Nested if In many cases we can have several ifs one inside other if. This is called to "nest" if into each other and can have all the levels that we need, but the more levels that we have the more difficult is to read the code. All of them should have their own sintax. Let's see some examples of nested ifs ```python= if potato == True: x = x+2 if egg == True: smashEggWithPotatos() y = y+1 ``` The difference here froom and elif //TO-DO ## Compounded if It's something usual that when using an if we don't use only one condition but several that have a relationship using logic gates (mostly "and", "or" and "not") In python those logic gates are writen as `and`, `or` and `not` Examples: ```python= if isWeekend or is ``` ### Bouncer example ```python= overAge = True weaponsCarried = True if overAge and not weaponsCarried: print("you're into the disco") else: print("you're not in") ``` ## Example program pass the IB diploma //TO-DO