{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Table of Contents\n", "[Conditionals](#Conditionals)\n", "1. [Introduction](#intro)\n", "2. [If and else](#if)\n", "3. [Operators](#operators)\n", "4. [Elif](#selif)\n", "\n", "[Iteration](#Iteration)\n", "1. [For](#for)\n", "2. [While](#while)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Conditionals\n", "\n", "\n", "## Introduction\n", "Imagine that you invite a few friends to dinner at your place. At the beginning of the meal, one guest calls your attention: \"I'm sorry, but I don't have any fork...\"\n", "\n", "Like everyone else, you will understand his request implicitly as: \"Could you please give me a fork?\"\n", "\n", "Since you are having dinner, you will also assume that the requested object is a small fork which is used to eat, of course not a farmer's fork...\n", "\n", "Therefore, you will go to your kitchen. If you don't find any fork there, you will probably stressed out for a few seconds then you will tell yourself: \"Well... Maybe I can borrow one from the neighbor...\"\n", "\n", "The bottom line of this story is that you have to keep in mind that your computer is not as clever as you. At least at our basic programming level, your computer is totally unable, inter alia, to understand any implicit assertion, to interpret an assertion according to the context, or to improvise in an unexpected situation.\n", "\n", "It means that you have to give him precise instructions about what to do in each possible situation. Fortunately, you use a programming language to speak to your computer. Programming languages, like Python, use specific predefined (in jargon : native) structures to deal with those cases. What will follow will show you how.\n", "\n", "The **conditionals** allow us to tell the computer what to do in specific situations.\n", "\n", "We will start with a concrete example: a user connection interface. To make the explanation easier to follow, let simplify the example as much as possible.\n", "\n", "\n", "## Application : User connection interface\n", "## If and else\n", "We will basically define an ID and a password that will be required to connect to our fictitious server. In a real situation, the user would have registered those informations previously. Don’t forget to add **\"\"** around the desired terms to set their type as strings." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "ID = \"Euler\"\n", "password = \"271\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, we need to define the data given by the user. We use the function input to let the user type his personal information." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your ID : 564\n", "Enter your password : 444\n" ] } ], "source": [ "ID = \"Euler\"\n", "password = \"271\"\n", "\n", "user_ID = input(\"Enter your ID : \")\n", "user_password = input(\"Enter your password : \")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At this point, there are two different situations. The user may either gives the required informations, or he may not. In the former situation, he will successfully connect. In the latter, he will not have access to the program. We can represent the case in the following pseudocode.\n", "```\n", "If user gives correct informations:\n", " access the program\n", "Else:\n", " don't access the program\n", "```\n", "\n", "In our simplified example, we only have one registered user. Now, let assume now that they are plenty of them. To successfully connect, our users must give the correct ID AND the correct password. This means that the given ID must be equal to the registered ID as well as the given password must be equal to the registered one. In addition, a message will be printed to enable the user to understand whether or not the connection was succesful.\n", "\n", "Let's insert the printing task into our pseudocode:\n", "```\n", "If ID is the same as user_ID AND password is the same as user_password:\n", " print : Welcome (user_name) ! You are connected.\n", " access the program\n", "Else:\n", " print : Invalid ID or password\n", " don't access the program\n", "```\n", "\n", "Python is a programming language that is very intuitive to use. The defined Python syntax for the conditionals is quite similar to what we have written in our pseudocode. It looks like this:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ID or password are invalid\n" ] } ], "source": [ "if ID == user_ID and password == user_password: #Both inputs are correct\n", " print(\"Welcome {} ! You are connected.\".format(user_ID)) #the method format inserts elements into the brackets\n", " user_connected = True\n", "else: #The condition, that both ID and Password are correct, is not met\n", " print(\"ID or password are invalid\")\n", " user_connected = False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Yes you can](imgs/04_Yes_you_can.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What have we done so far? We have used the conditionals **if** and **else** to differentiate the two situations.\n", "\n", "Then, we have defined a new `user_connected` variable which, if wanted, may be used later on to let the user continue in the program.\n", "\n", "**if** and **else** have the following use in our little example: \n", "\n", "1. **if** : If the user types the correct ID **and** the correct password, he will get a personalized welcoming message and the variable `user_connected` will be **True**.\n", "\n", "2. **else** : In all other situations, he will get a personalized failure message and `user_connected` will be **False**.\n", "\n", "Each of those two conditions is exclusive. Python will execute either the **if** (and subsumed tabulated lines), or the **else**. It will never do both.\n", "\n", "You can check it by running the following code. You just have to select the cell and press ⌃↩. Try all situations with correct and incorrect informations.\n", "\n", "PS : We add the last line to let you check if the user is connected or not. If you get **True**, the user is virtually connected; if you get **False**, he is not." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your ID : Toni\n", "Enter your password : 25\n", "invalid ID or password\n", "False\n" ] } ], "source": [ "ID = \"Euler\"\n", "password = \"271\"\n", "\n", "user_ID = input(\"Enter your ID : \")\n", "user_password = input(\"Enter your password : \")\n", "\n", "if ID == user_ID and password == user_password: #Both inputs are correct\n", "\tprint(\"Welcome {} ! You are connected.\".format(user_ID))\n", "\tuser_connected = True\n", "else:\n", "\tprint(\"invalid ID or password\") #The condition, that both ID and Password are correct, is not met\n", "\tuser_connected = False\n", "\n", "print(user_connected)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Digression : Operators\n", "As you have probably noticed, we use a specific sign to make Python understand that two objects are equals : the sign **==**.\n", "This is an operator.\n", "We don't use **=** because this sign already have another meaning in Python. It means that we attribute a value to a variable. For more information, take a look at the ad hoc tutorial.\n", "\n", "The operators are often quite intuitive. Here is a list of the most commonly used comparison and logical operators:\n", "Comparison Operator | Signification\n", "-------- | -----------\n", "A == B| If the values of A and B are equal, then the condition becomes true.\n", "A != B| If values of A and B are not equal, then condition becomes true.\n", "A > B| If the value of A is greater than the value of B, then condition becomes true.\n", "A < B| If the value of A is less than the value of B, then condition becomes true.\n", "A >= B| If the value of A is greater than or equal to the value of B, then condition becomes true.\n", "A <= B| If the value of A is less than or equal to the value of B, then condition becomes true.\n", "\n", "Logical Operator | Signification\n", "---------------- | -----------\n", "A and B| If both A and B are true then condition becomes true.\n", "A or B| If A is true, or B is true, or both are true then condition becomes true.\n", "not A| Used to reverse the logical state of its operand.\n", "\n", "\n", "## Back to application : User connection interface\n", "## Elif\n", "As you may think, two conditions are not enough. Indeed, the user knows that he entered an incorrect ID or password, but he does not know which one is incorrect (or if both are incorrect).\n", "\n", "Consequently, in Python, we can add a supplementary exclusive conditional called: **elif**. It is an abreviation for the terms 'else if'. In addition, please understand that Python read an **elif** only if the previous condition is **False**. It quite makes sense since **else** means that the first conditions is false.\n", "\n", "You can check the new code by running the following cell:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your ID : John\n", "Enter your password : ddd\n", "Both ID and password are invalid. Please enter correct informations.\n", "False\n" ] } ], "source": [ "ID = \"Euler\"\n", "password = \"271\"\n", "\n", "user_ID = input(\"Enter your ID : \")\n", "user_password = input(\"Enter your password : \")\n", "\n", "if ID == user_ID and password == user_password: #Both inputs are correct\n", " print(\"Welcome {} ! You are connected.\".format(user_ID))\n", " user_connected = True\n", "elif ID != user_ID and password == user_password: #Only the ID is not correct\n", " print(\"Invalid ID. Please enter a correct ID.\")\n", " user_connected = False\n", "elif ID == user_ID and password != user_password: #Only the Password is not correct\n", " print(\"Invalid password. Please enter a correct password.\")\n", " user_connected = False\n", "elif ID != user_ID and password != user_password: #Both inputs are not correct\n", " print(\"Both ID and password are invalid. Please enter correct informations.\")\n", " user_connected = False\n", "\n", "print(user_connected)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our code follow this path :\n", "\n", "1. **if** (first situation): If the user types the correct ID **and** the correct password, he will get a personalized welcoming message and the variable `user_connected` would be **True**.\n", "\n", "\n", "2. **elif** (second situation) : Else, if only the ID is incorrect, the user he will get an ad hoc message and `user_connected` will be **False**.\n", "\n", "\n", "3. **elif** (third situation) : Else, if only the password is incorrect, the user he will get an ad hoc message and `user_connected` will be **False**.\n", "\n", "\n", "4. **elif** (fourth situation) : Else, if both ID and password are incorrect, the user he will get an ad hoc message and `user_connected` will be **False**.\n", "\n", "This code does work; nevertheless, it's not very well designed. As you can see, several lines are copy-pasted. In this example, it is not cumbersome since we only have four situations. However, imagine if you have hundreds of situations and thousands of lines of code, it may be hardly manageable. \n", "\n", "*As a principle, you should avoid having several times the same line*.\n", "*In Jargon: You should keep your Code **DRY** (**D**on't **R**epeat **Y**ourself!)*\n", "\n", "Let's improve our code in order to delete copy-pasted lines:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your ID : Euler\n", "Enter your password : 271\n", "Welcome Euler ! You are connected.\n", "True\n" ] } ], "source": [ "ID = \"Euler\"\n", "password = \"271\"\n", "\n", "user_ID = input(\"Enter your ID : \")\n", "user_password = input(\"Enter your password : \")\n", "\n", "if ID == user_ID and password == user_password: #Both inputs are correct\n", " print(\"Welcome {} ! You are connected.\".format(user_ID))\n", " user_connected = True\n", "else: \n", " if ID != user_ID and password != user_password: #Both inputs are not correct\n", " invalid_item = \"ID and password\"\n", " elif ID != user_ID: #Only the ID is not correct\n", " invalid_item = \"ID\"\n", " elif password != user_password: #Only the password is not correct\n", " invalid_item = \"password\"\n", " print(\"Invalid {}. Please enter a valid {}\".format(invalid_item, invalid_item)) \n", " user_connected = False\n", "\n", "print(user_connected)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our code follows this path :\n", "\n", "1. **if** : If the user types the correct ID **and** the correct password, he will get a personalized welcoming message and the variable `user_connected` would be **True**.\n", "\n", "\n", "2. **else** : Else, `user_connected` will be **False** and the user will get a message telling him that he has entered invalid information. This message tells him what is invalid depending on the value of the variable `invalid_item` in the following sub-conditions : \n", "\n", " 2.1 **if** : If both ID and password are incorrect, `invalid_item` will take the value \"ID and password\"\n", " \n", " 2.2 **elif** : Else, if only ID is incorrect, `invalid_item` will take the value \"ID\"\n", " \n", " 2.3 **elif** : Else, if only password is incorrect, `invalid_item` will take the value \"password\"\n", "\n", "At this point, you may ask yourself : \"Wait... There are four situations. Why don't we replace the last **elif** with an **else**?\"\n", "\n", "It is a good point! From what we have seen so far, you are right. Nevertheless, a rule in programming is that you should not blindly trust the user. He may do something unexpected. In this case, you will get an error message from the system. For you, it's nothing much; it will even help you to find your mistake. However, the user is not supposed to know how to react in those kind of situations. It could be quite a frustrating experience for him. That's not what you want, right?\n", "\n", "Consequently, it is more favorable to put an **elif** and then add a final **else** in order to deal with any unexpected error. The user will not get any further information about his mistake, but at least, he will not get an incomprehensible message error from the system.\n", "\n", "If you have time to waste, you can try printing the last message by entering some unexpected input. Good luck!" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your ID : John\n", "Enter your password : ??\n", "Invalid ID and password. Please enter a valid ID and password\n", "False\n" ] } ], "source": [ "ID = \"Euler\"\n", "password = \"271\"\n", "\n", "user_ID = input(\"Enter your ID : \")\n", "user_password = input(\"Enter your password : \")\n", "\n", "if ID == user_ID and password == user_password:\n", " print(\"Welcome {} ! You are connected.\".format(user_ID))\n", " user_connected = True\n", "else: \n", " if ID != user_ID and password != user_password:\n", " invalid_item = \"ID and password\"\n", " elif ID != user_ID:\n", " invalid_item = \"ID\"\n", " elif password != user_password:\n", " invalid_item = \"password\"\n", " else:\n", " invalid_item = \"data\"\n", " print(\"Something went wrong. Please retry to submit your ID and password.\")\n", " print(\"Invalid {}. Please enter a valid {}\".format(invalid_item, invalid_item))\n", " user_connected = False\n", "\n", "print(user_connected)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## To sum up what we have learned about conditionals\n", "1. Always start with an **if** to create your first condition. Don't forget to add `:` at the end of the line. Python will automatically add a tabulation to the following line. All the following lines with this tabulation will be included in you first condition.\n", "\n", "2. Then you can create other conditions by adding as many **elif** as you like. You can also start new chains by adding new **if**.\n", " * Python will read an **elif** only if the previous condition is **False**. \n", " * Python will always read an **if** (of course, it will not always execute the subsumed instruction; only if the condition is **True**...)\n", " \n", " Keep in mind that each **if** or **elif** is a new condition; thus, you have to return to the same tabulation level than the first **if**.\n", "\n", "3. At the end, you can put an **else** for all other situations. (Attention, an **else** only refers to the **last** **if**.)\n", "\n", " If you're working with a user input, it's recommended to finish with an **else** in order to deal with all the other (unexpected) situations.\n", "\n", "To make sure that you master the conditionals, you can play with the following code by changing parameters `B`, `C`, `D` and try to predict what will be the output:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A is not equal to D\n" ] } ], "source": [ "A = 1\n", "B = 0\n", "C = 0\n", "D = 0\n", "\n", "if A == B:\n", " print(\"A is equal to B\") #always read (of, only executed if A==B)\n", "if A == C:\n", " print(\"A is equal to C\") #always read\n", "elif A == D:\n", " print(\"A is equal to D, but not to C\") #only read if A!=C, independent from A==B\n", "if A == D:\n", " print(\"A is equal to D\") #always read\n", "else:\n", " print(\"A is not equal to D\") #only refer to A==D, not to A==B or A==C !" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Iteration\n", "In programming, there are two main methods to execute a task multiple times, we use the **for** –loop as well as the **while**-loop; The recursion method is also an iteration; however, it will unfortunatly not be covered in this tutorial\n", "\n", "\n", "## For\n", "Imagine you have a list, which you can give whatever name you want. Also, this list may contain any variables you like. In the example below, let us call the list `elements` and insert several car brands.\n", "\n", "It is important to say that For-loops can be used with many different types of objects. These are called iterable objects. For now, let's stick to the list you can see below." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "elements = [\"VW\" , \"Porsche\" , \"Toyota\" , \"Mercedes\" , \"Chevrolet\" ,\"Suzuki\" ]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To print every element separatly, we can go through the list systematically. For this task though, we need to use a second variable - e.g. we can use following method:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "VW\n", "Porsche\n", "Toyota\n", "Mercedes\n", "Chevrolet\n", "Suzuki\n" ] } ], "source": [ "for carname in elements:\n", " print(carname)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "At every point in the list, we assign a value from the list to the variable `carname` and print it at the end. It's comparable to a box filled with a lot of stuff. The variable `carname` represents an object you just took out of that box and you compare it to a given criteria - e.g. is the object eatable or not.\n", "\n", "Keep in mind that the name `carname` is totally arbitrary. You can name it `BenficaIsTheBestFootballTeamInEurope`; it will work to !\n", "\n", "There is also the possibility to **loop through** a set of numbers at a **set range**. For example, if you want to print all numbers, which are a multiple of 3 until it reaches of number 100, you can use the **for**-loop with an easy approach." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "6\n", "9\n", "12\n", "15\n", "18\n", "21\n", "24\n", "27\n", "30\n", "33\n", "36\n", "39\n", "42\n", "45\n", "48\n", "51\n", "54\n", "57\n", "60\n", "63\n", "66\n", "69\n", "72\n", "75\n", "78\n", "81\n", "84\n", "87\n", "90\n", "93\n", "96\n", "99\n" ] } ], "source": [ "for x in range(3,100,3): # range(3, 100, 3) <=> from 3 to 100, only multiples of 3\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Within the range function, we define the starting point, the end point as well as the interval, we use to add to our starting point.\n", "\n", "### Break-Statement\n", "If we are interested in a particular value of the list, and we want to stop the loop at a given value from continuing, we can use the so-called **break** statement. With the help of the **break** statement, we can leave the **for**-loop and continue with the next non tabulated line of code in our program. This **break** statement looks as following:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "VW\n", "Porsche\n", "reached break-command\n" ] } ], "source": [ "for carname in elements:\n", " if carname == \"Toyota\":\n", " print(\"reached break-command\")\n", " break\n", " else:\n", " print(carname)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "You can compare the **break** statement to searching a box for a certain element or certain number of elements. When you find whatever you were looking for, or you have taken the amount of things out of the box you needed, you stop searching for any other items and you go to the next task.\n", "\n", "### Continue-Statement\n", "If our program should execute a piece of code for every value except a particular one, we can use the **continue** statement. **Continue**, therefore, helps us to skip certain values of the **for**-loop. For example, you roam through a box and for every item you take out of this box, you do a certain task, let's say put it in another box. Nevertheless, if you find a specific item that you don’t want in the new box, you just skip it." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "VW\n", "Porsche\n", "we wont print this carname, but continue the loop\n", "Mercedes\n", "Chevrolet\n", "Suzuki\n" ] } ], "source": [ "for carname in elements:\n", " if carname == \"Toyota\":\n", " print(\"we wont print this carname, but continue the loop\")\n", " continue\n", " else:\n", " print(carname)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Else-Statement\n", "With the help of the **else** statement at the end of a loop, we can execute a certain step of code. Imagine you roam through a box of things where you take every item out. Thanks to the **else** statement you can put a piece of paper inside the box with a message." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "VW\n", "Porsche\n", "Toyota\n", "Mercedes\n", "Chevrolet\n", "Suzuki\n", "all items were checked\n" ] } ], "source": [ "for carname in elements:\n", " print(carname)\n", "else:\n", " print(\"all items were checked\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## While\n", "With the **while**-loop, we get the possibility to loop through a piece of code a finite or an infinite number of times. It is defined by a true or false statement. Imagine, for example, that you drive your car on the street. While driving, you should check your speed systematically. In a code, this example would look this :\n", "\n", "*PS: The following example is just an analogy. Do not run the cells because the functions are not defined.*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "while driving():\n", " checkSpeed()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Where `driving()` and `checkSpeed()` represent two defined functions. \n", "The **while**-loop consists of the same functionalities as the **for**-loop.\n", "\n", "\n", "### Break-statement\n", "If you want to stop the loop, e.g. whenever a certain value occurs, you can use the **break** statement. Imagine again that you arrive at your destination, you will stop your car and leave. In code, this will look like this:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "while driving():\n", " if atDestination():\n", " print(\"Arrived at your destination\")\n", " break\n", " else:\n", " checkSpeed()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Continue-statement\n", "The **break** statement interrupts the loop and quits it. The second method is similar to the **continue** statement of the for-loop. With the continue-statement we can **skip a certain case** in our loop. For instance, while you are driving, there is a car, which breaks all the rules and hustles you in your lane, you can ignore him. In the while loop this looks like this:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "while driving():\n", " checkSpeed()\n", " if meanDriverArrives():\n", " continue\n", " else:\n", " checkSpeed()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## To sum up what we have learned about iteration\n", "Most importantly, we have to remember the different applications of the for and the while loop.\n", "\n", " **for** | **while**\n", "------ | -------\n", "The **for**-loop is used where we already know about the number of times loop needs to be excuted |The **while**-loop is used in situations where we do not know how many times loop needs to be excuted beforehand.\n", "\n", " **continue** Statements keep iterating after a certain value was found.\n", "\n", " **break** Statements will stop the iteration after a certain value was found.\n", "\n", "Thanks to this introduction into the iteration you should now be able to handle the most important things of this topic.\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }