1126 lines
37 KiB
Plaintext
1126 lines
37 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Simple coding"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 1 Introduction"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Software makes the world go round. Cars and TVs have software that controls how they work and global commerce and finance are impossible without software that control the stocks, carry out payments, find the best transport route, etc.\n",
|
|
"\n",
|
|
"**Coding** (or programming) is the construction of software. Coding involves writing a 'recipe', which in computing is called an **algorithm**, in a so-called **programming language** that a computer can understand. When the computer **runs** the code we wrote, it follows the 'recipe', step by step.\n",
|
|
"\n",
|
|
"We will use Python, a popular programming language for teaching and for professional software development. You will see that Python code reads almost like plain English. Writing simple programs in Python is not very difficult, once you have come up with the 'recipe', the algorithm.\n",
|
|
"\n",
|
|
"This tutorial shows how to code in Python the basic building blocks of all algorithms, and how to ask the user for input and produce some output on the screen. The skills, concepts and jargon (in boldface) you will learn are the foundations for coding all sorts of apps in all sorts of languages, not just Python.\n",
|
|
"\n",
|
|
"You won't have to install any software, the code examples are embedded in this course, and you can execute and change them right here.\n",
|
|
"\n",
|
|
"> Wherever 'Run Python' appears we recommend that you open the link in a new tab and work from there.\n",
|
|
"\n",
|
|
"Go ahead, click 'Run' (the ► icon) to execute the following program (I'll explain it later). You should see a message showing the output of running the code."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"The sum of 3 and 7 is 10\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"result = 3 + 7\n",
|
|
"print(\"The sum of 3 and 7 is\", result)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"You can also change the code. Click with the mouse next to the 7 on the first line, and use the keyboard to replace it by 2 (or another number of your choice). Also replace the 7 in the second line by the same number. Click again on 'Run'. The message should now read \"The sum of 3 and 2 is 5\", or similar."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"The sum of 3 and 2 is 5\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"result = 3 + 2\n",
|
|
"print(\"The sum of 3 and 2 is\", result)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In the rest of this tutorial I won't repeat that after you change a program you need to run it to see what it produces.\n",
|
|
"\n",
|
|
"I will show you various small programs with exercises for you to practice your coding skills, by modifying or building upon my programs. You can share your code with friends and family by clicking on the down arrow next to 'Share'.\n",
|
|
"\n",
|
|
"If, whilst practicing, you do any mistakes, you can always undo your all your changes. Click on the 3 lines icon on the top left corner. A menu appears. Click on 'Reset' and confirm you want to put back the code as it was, before you changed the numbers.\n",
|
|
"\n",
|
|
"All done? Good. In the next section we will start learning to code."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 2 Sequence"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The simplest Python program is a **sequence** of **instructions**, written one per line, and executed one by one from top to bottom. Our first program only has two instructions. Here is the program again, already run for you. (You may need to just see the result of running the code. To see the code itself, click on the pencil icon.)\n",
|
|
"\n",
|
|
"Remember to open the link to Python in a new tab."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"The sum of 3 + 7 is 10\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"result = 3 + 7\n",
|
|
"print(\"The sum of 3 + 7 is\",result)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The first instruction is an **assignment**: the computer evaluates the **expression** to the right of the assignment (=) and stores the result in the **variable** on the left of the assignment. Each piece of data we need has to be stored in a variable. Translating Python to English, the assignment states 'let the result be the sum of 3 and 7'.\n",
|
|
"\n",
|
|
"The second instruction, print, prints some text on the screen, followed by the computed result. Note the following:\n",
|
|
"\n",
|
|
"- the comma separates the two things to be printed, in the same way we use commas in English to enumerate two, three, or more things;\n",
|
|
"- text is written between double-quotes, which are not printed themselves. In Python, a sequence of characters surrounded by double-quotes is called a **string**."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 2.1 The art of failure\n",
|
|
"\n",
|
|
"The following details are important once you start writing code. Computers are not as smart and accommodating as human readers: at the slightest spelling mistake (like pint instead of print) or missing punctuation (forgetting the comma or double-quotes, for example), the computer will give up on understanding and running your code and will display an error message.\n",
|
|
"\n",
|
|
"On top of that, most errors are rather cryptic. Hence it's best to get used to them, by doing errors on purpose, so that you have a clue what might be wrong when you are writing your own code."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 1**\n",
|
|
">\n",
|
|
"> Put double quotes around the 7 on the first line and run the program. You will get an error message saying there is a **type error**. This basically means the code is mixing data of different types, mixing apples and oranges if you like. In this case, we are trying to add a number (`3`) to a string (`\"7\"`) which of course doesn't make sense. Click on the X at the right end of the message to make it go away and then reset the program to undo the change."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"ename": "TypeError",
|
|
"evalue": "unsupported operand type(s) for +: 'int' and 'str'",
|
|
"output_type": "error",
|
|
"traceback": [
|
|
"\u001b[31m---------------------------------------------------------------------------\u001b[39m",
|
|
"\u001b[31mTypeError\u001b[39m Traceback (most recent call last)",
|
|
"\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[7]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m result = \u001b[32;43m3\u001b[39;49m\u001b[43m \u001b[49m\u001b[43m+\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43m7\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\n\u001b[32m 2\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33m\"\u001b[39m\u001b[33mThe sum of 3 + 7 is\u001b[39m\u001b[33m\"\u001b[39m,result)\n",
|
|
"\u001b[31mTypeError\u001b[39m: unsupported operand type(s) for +: 'int' and 'str'"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"result = 3 + \"7\"\n",
|
|
"print(\"The sum of 3 + 7 is\",result)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Sometimes, code has more subtle errors, that lead to unexpected results. This is akin to miscommunication, when other people understand something different from what you intended to say. Here is an example."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 2**\n",
|
|
">\n",
|
|
"> Put double quotes around the variable name in the second line. Run the program. Try to explain what happened before further reading."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"The sum of 3 + 7 is result\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"result = 3 + 7\n",
|
|
"print(\"The sum of 3 + 7 is\",\"result\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"*What has happened is that Python is interpreting the result as a string, rather than a variable making it so that the outputted data reads \"the sum of 3 + 7 is result\", instead of \"the sum of 3 + 7 is 10\".*"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"When putting double-quotes around a variable name, it becomes a string. Hence, the computer will print the name literally, instead of printing the value stored in the variable.\n",
|
|
"\n",
|
|
"To sum up, `\"result\"`, `\"7\"`, `result` and `7` are different things: the first two are strings (literal text), the third is a variable, and the last is a number.\n",
|
|
"\n",
|
|
"Learning from mistakes is always helpful, so for this and the remaining programs in this tutorial, I encourage you to introduce errors and observe what message or output you get. Don't forget to reset the program after each error.\n",
|
|
"\n",
|
|
"In a sequence, *all* instructions are executed. Next you will learn how to selectively execute some instructions but not others."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 3 Selection"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Further investigate the Python programming language by learning about conditions.\n",
|
|
"\n",
|
|
"Let's imagine we are developing software for a restaurant, where a tip of 10% is added to the bill. Here's the code, a simple sequence of assignments and output. For example, the assignment on line 3 states 'let the tip be the expense multiplied by the percentage'. Note that in Python the **multiplication operator is the asterisk."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 15,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 59.4\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"percentage = 0.10\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Let's further assume the tip is only automatically added for groups above 6 people. We need one more variable, to store the number of people in the group, and one new instruction to handle both cases: *if* the number of people is more than 6, the percentage is 10%, otherwise it's 0%."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 14,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 59.4\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 7\n",
|
|
"if people > 6:\n",
|
|
" percentage = 0.10\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Before I explain the code, let's **test** it, to make sure it works as intended. Large software companies employ many testers to check their code. Good testing includes choosing enough inputs (preferably borderline cases) to exercise all possible conditions. In this case, we should at least test for 6 and 7 people, the borderlines where the tip percentage changes."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 3**\n",
|
|
">\n",
|
|
"> Change the number of people to six and confirm the bill is just the expenses in that case.\n",
|
|
">\n",
|
|
"> Notice that there is a colon (`:`) at the end of the `if` and `else` lines. Forgetting the colons and forgetting to indent the instructions will lead to error messages."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 16,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 54\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 6\n",
|
|
"if people > 6:\n",
|
|
" percentage = 0.10\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 17,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 59.4\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 7\n",
|
|
"if people > 6:\n",
|
|
" percentage = 0.10\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The **selection** instruction '`if` condition: block `else:` block' chooses which block to execute as follows. The computer then executes the **block** of code (the indented instructions) belonging to the if part. If the condition is false, the computer executes *instead* the `else` block. The indentation is needed to know which instructions belong to which part. Afterwards the computer continues executing the non-indented instructions."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 3.1 And now for something not completely different"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Usually there are many ways to solve the same problem. For the problem of adding the 10% tip only to groups over 6 people, we have set up the tip rate to 0% or 10% or the tip itself but we can change how the tip is calculated."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 4**\n",
|
|
">\n",
|
|
"> Keep the rate at 10% but change the way the tip is computed: if there are more than 6 people, let the tip be the expense times the rate, otherwise let the tip be zero. Change the code accordingly and check your solution against mine."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Finally, let's assume the restaurant decides to impose a higher tip of 15% for groups of at least 15 people. In Python we can chain various conditions as follows:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 29,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 59.4\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 7\n",
|
|
"if people >= 15:\n",
|
|
" percentage = 0.15\n",
|
|
"elif people > 6:\n",
|
|
"\tpercentage = 0.1\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In plain English: if the number of people is larger or equal (>=) to 15, let the percentage be 15%, other if (`elif`, *not* `else if`) it is larger than 6 let the percentage be 10%, otherwise let the percentage be 0%."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 5**\n",
|
|
">\n",
|
|
"> Test the code with the four borderline cases: 6, 7, 14 and 15 people."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 30,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 54\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 6\n",
|
|
"if people >= 15:\n",
|
|
" percentage = 0.15\n",
|
|
"elif people > 6:\n",
|
|
"\tpercentage = 0.1\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 31,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 59.4\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 7\n",
|
|
"if people >= 15:\n",
|
|
" percentage = 0.15\n",
|
|
"elif people > 6:\n",
|
|
"\tpercentage = 0.1\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 32,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 59.4\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 14\n",
|
|
"if people >= 15:\n",
|
|
" percentage = 0.15\n",
|
|
"elif people > 6:\n",
|
|
"\tpercentage = 0.1\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 33,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 62.1\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 15\n",
|
|
"if people >= 15:\n",
|
|
" percentage = 0.15\n",
|
|
"elif people > 6:\n",
|
|
"\tpercentage = 0.1\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Note that the order in which we write the conditions is important, because the computer checks them from top to bottom and executes only *one* block, for the *first* condition that is true. The `else` block has no condition, so it's a 'catch all' in case no condition is true."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 6**\n",
|
|
">\n",
|
|
"> Explain why the following code is wrong. Hint: repeat the tests and see what happens. That's what tests are for.\n",
|
|
"\n",
|
|
"```python\n",
|
|
"expenses = 54\n",
|
|
"people = 2\n",
|
|
"if people > 6:\n",
|
|
" percentage = 0.10\n",
|
|
"elif people >= 15:\n",
|
|
" percentage = 0.15\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print \"Total bill:\", bill\n",
|
|
"```"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"*The code above is incorrect due to the order of operations. With the execution of the code, it will never correctly add 15% tip even if the number of people is equal to or greater than 15. To fix the code, the order needs to be changed so that the `people >= 15` is first, then `people = 6` so that the calculation can account for when the bill has equal to or greater than 15 people.*"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 4 Iteration (Part 1)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In this section you will learn about repetition in the Python programming language.\n",
|
|
"\n",
|
|
"A restaurant bill is made from the various food and drink items ordered. Our program should sum those prices to obtain the expenses, on which the tip will be added. The algorithm (which is independent of any programming language) is as follows.\n",
|
|
"\n",
|
|
"1. Let items be a list of the prices of the food and drinks ordered.\n",
|
|
"2. Let the expenses be zero.\n",
|
|
"3. For each item in the items list:\n",
|
|
" 1. add it to the expenses.\n",
|
|
"4. print the expenses.\n",
|
|
"\n",
|
|
"Step 3 is called an **iteration**: it goes through the list to process each item. This can be directly translated to Python."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 38,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Food and drinks: 54.0\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# Let the items be a list of the prices of the food and drinks ordered.\n",
|
|
"items = [4.35, 2, 19.95, 22.70, 5] # same total as before: 54\n",
|
|
"# Let the expenses be zero.\n",
|
|
"expenses = 0\n",
|
|
"# For each item in the items list:\n",
|
|
"for item in items:\n",
|
|
" # Add it to the expenses.\n",
|
|
" expenses = expenses + item\n",
|
|
"# Print the expenses.\n",
|
|
"print(\"Food and drinks:\", expenses)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In Python, any line starting with # is a **comment**. The computer ignores comments, they are just notes by the code's author (or someone else) to clarify any finer points. Such notes come in very handy if the author (or someone else) needs to change the code later.\n",
|
|
"\n",
|
|
"In Python, **lists** are simply comma-separated values, within square brackets.\n",
|
|
"\n",
|
|
"The 'for variable in list: block' instruction goes through the given list and successfully stores each value of the list in the variable and then executes the block, which will usually (but not always, see exercise below) refer to the variable to get its value. In this case, I add the value of the item to the current expenses and store the result again in expenses, so that it is always up to date. In English: let the new expenses be the old expenses plus the item you ordered."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 7**\n",
|
|
">\n",
|
|
"> Calculate and print how many items were ordered, i.e. 5 in the example above. First change the algorithm, then translate it to code. Hint: you need to coun the items in the list, their prices are irrelevant. If you get stuck, you can see the algorithm."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 44,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"number of items ordered: 5\n",
|
|
"Food and drinks: 54.0\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# Let the items be a list of the prices of the food and drinks ordered.\n",
|
|
"items = [4.35, 2, 19.95, 22.70, 5] # same total as before: 54\n",
|
|
"# Let the expenses be zero.\n",
|
|
"expenses = 0\n",
|
|
"# For each item in the items list:\n",
|
|
"for item in items:\n",
|
|
" # Add it to the expenses.\n",
|
|
" expenses = expenses + item\n",
|
|
"itemcount = len(items)\n",
|
|
"\n",
|
|
"print(\"number of items ordered:\", itemcount)\n",
|
|
"# Print the expenses.\n",
|
|
"print(\"Food and drinks:\", expenses)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 5 Functions"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In this section you will learn about functions in the Python programming language.\n",
|
|
"\n",
|
|
"Totting up the bill is basically calculating the sum of a list of numbers. This is such a common need that Python already provides a **function** for that, appropriately called `sum`. A function takes some data (the function's input) and returns some other data (the function's output). In this case, the `sum` function takes a list of numbers as input and returns a single number as output.\n",
|
|
"\n",
|
|
"To apply a function to some data (whether it's a variable, a number or a string), just write the name of the function followed by the data in parentheses. The computer will calculate the function's output, which can be used in further calculations or assigned to a variable."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 45,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Food and drinks: 54.0\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"items = [4.35, 2, 19.95, 22.70, 5]\n",
|
|
"expenses = sum(items)\n",
|
|
"print(\"Food and drinks:\", expenses)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"As you can see, using the `sum` function shortens our code and makes it easier to understand, because the function's name explicitly states what the code is doing. Good programmers don't just write code, they write *readable* code. They know that code always changes to accommodate further customer requests, and trying to modify cryptic code you wrote some weeks or months ago is no fun. Using comments and descriptive names for variables and functions helps make code readable.\n",
|
|
"\n",
|
|
"**The length function**\n",
|
|
"\n",
|
|
"Counting the number of items in a list is also so common, that Python has a function for that too, called `len`, which returns the length of the list.\n",
|
|
"\n",
|
|
"Change the code above to show the number of ordered items, using the `len` function."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 46,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Food and drinks: 54.0\n",
|
|
"Number of food and drinks: 5\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"items = [4.35, 2, 19.95, 22.70, 5]\n",
|
|
"expenses = sum(items)\n",
|
|
"numberofitems = len(items)\n",
|
|
"print(\"Food and drinks:\", expenses)\n",
|
|
"print(\"Number of food and drinks:\", numberofitems)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 5.1 The input function"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Another very useful function is `input`: it takes a string that it prints on the screen (the user's prompt), and returns a string with what the user typed on the keyboard until they pressed the RETURN or ENTER key. Run the code below and type in your name, followed by RETURN or ENTER."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"name = input(\"What's your name?\")\n",
|
|
"print(f\"Nice to meet you,\", name)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Note that `input` always returns a string, even if the user typed a number. To see the implications of that run the code below and type in your birth year."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"year = input(\"In what year were you born?\")\n",
|
|
"print (\"Your age is\", 2022 - year)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The computer reports a type error, because the code is mixing two different types of data. It is trying to subtract the string by `input` from the number 2022."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 5.2 A conversion function"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The solution is to use the built-in function `int` that takes a string and converts it into an **integer**, which is a number like -2, -1, 0, 1, 2, etc. If the string repeats a decimal number, `int` will give an error."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"answer = input(\"In what year were you born?\")\n",
|
|
"year = int(answer)\n",
|
|
"print (\"Your age is\", 2022 - year)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 8**\n",
|
|
">\n",
|
|
"> Change the restaurant program (repeated below) so that it asks the user for the number of people.\n",
|
|
"> "
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Total bill: 62.1\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"expenses = 54\n",
|
|
"people = 0\n",
|
|
"people = input(\"How many people are eating today? \")\n",
|
|
"customers = int(people)\n",
|
|
"if customers >= 15:\n",
|
|
" percentage = 0.15\n",
|
|
"elif customers > 6:\n",
|
|
" percentage = 0.10\n",
|
|
"else:\n",
|
|
" percentage = 0\n",
|
|
"tip = expenses * percentage\n",
|
|
"bill = expenses + tip\n",
|
|
"print(\"Total bill:\", bill)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Next, in Section 6, you'll learn a different form of iteration."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## 6 Iteration (part 2)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In this section you will learn more about iteration and repetition in the Python programming language.\n",
|
|
"\n",
|
|
"Let's use input to ask for the price of orders instead of fixing them in a list. This requires a new iteration: an infinite loop that keeps asking until the user types 'stop', for example. We also need to convert the string returned by input into a number we can add into the expenses. The algorithm is:\n",
|
|
"\n",
|
|
"1. let the expenses be zero\n",
|
|
"2. forever repeating the following:\n",
|
|
" 1. let answer be the reply to the question \"Price of ordered item?\"\n",
|
|
" 2. if the answer is equal to \"stop\":\n",
|
|
" - exit the loop\n",
|
|
" 3. otherwise:\n",
|
|
" 1. let the price be the answer converted to a decimal number\n",
|
|
" 2. add the price to the expenses\n",
|
|
"\n",
|
|
"Test the code below: provide the same values as before (4.35, 2, 19.95, 22.70 and 5), followed by stop, and check the sum is at the end 54."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"expenses = 0\n",
|
|
"while True:\n",
|
|
" answer = input(\"Price of ordered item?\")\n",
|
|
" if answer == \"stop\":\n",
|
|
" break\n",
|
|
" else:\n",
|
|
" price = float(answer)\n",
|
|
" expenses = expenses + price\n",
|
|
"print(\"Total of orders:\", expenses)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In Python, the 'while condition: block' instruction keeps executing the block while the condition is true. In this case the condition is always True (note the initial uppercase), which leads to an infinite loop. Doing forever the same thing can get a bit tedious, so at some point I have to break free with the appropriately named break instruction. At that point the computer starts executing whatever code follows the loop.\n",
|
|
"\n",
|
|
"Note that food and drink prices may be in pence or cents, so I need to convert the user's input string to a decimal number (called a **floating point** number in Python), using the function `float` instead of `int`.\n",
|
|
"\n",
|
|
"Note also that to check if two values or variables are equal, we write two equals signs, because a single equal sign is the assignment instruction."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 9**\n",
|
|
">\n",
|
|
"> Put a complete program together, that starts as above, then asks the user for the number of people in the group, computes the tip and the VAT (20% on the expenses) and finally prints out the total bill."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Tip Percentage 15.0 %\n",
|
|
"Tip: 8.1\n",
|
|
"20% VAT: 12.42\n",
|
|
"Total of orders: 54.0\n",
|
|
"Grand Total: 74.52\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# Program Variables\n",
|
|
"expenses = 0.0\n",
|
|
"value_added_tax = 0.2\n",
|
|
"number_of_customers = 0\n",
|
|
"tip_percentage = 0\n",
|
|
"\n",
|
|
"# Copied from Activity 8, old logic for getting the pricing of items.\n",
|
|
"while True:\n",
|
|
"\tuser_input = input(\"Price of ordered item? \")\n",
|
|
"\tif user_input == \"stop\":\n",
|
|
"\t\tbreak\n",
|
|
"\ttry:\n",
|
|
"\t\titem_price = float(user_input)\n",
|
|
"\t\texpenses += item_price\n",
|
|
"\texcept ValueError:\n",
|
|
"\t\tprint(\"Invalid input. Please enter a number or 'stop'.\")\n",
|
|
"\n",
|
|
"# Asking for the number of people in the group.\n",
|
|
"customers = input(\"How many people are in the group? \")\n",
|
|
"number_of_customers = int(customers)\n",
|
|
"\n",
|
|
"# Logic for calculating the tip_percentage\n",
|
|
"if number_of_customers >= 15:\n",
|
|
" tip_percentage = 0.15\n",
|
|
"elif number_of_customers > 6:\n",
|
|
" tip_percentage = 0.10\n",
|
|
"else:\n",
|
|
" tip_percentage = 0\n",
|
|
"\n",
|
|
"print(\"Tip Percentage\", tip_percentage * 100, \"%\")\n",
|
|
"tip = expenses * tip_percentage\n",
|
|
"print(\"Tip:\", round(tip, 2))\n",
|
|
"\n",
|
|
"vat = (expenses + tip) * value_added_tax\n",
|
|
"print(\"20% VAT:\", round(vat, 2))\n",
|
|
"\n",
|
|
"total_expenses = expenses + tip + vat\n",
|
|
"print(\"Total of orders:\", expenses)\n",
|
|
"\n",
|
|
"print(\"Grand Total:\", round(total_expenses, 2))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 6.1 The oldest algorithm"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The while loop condition doesn't have to always be true, of course. As an example, here is one of the oldest algorithms known, Euclid's algorithm, used to find the greatest common divisor of two integers greater than zero, i.e. the greatest number that divides both without any remainder. For example, the greatest common divisor of 3 and 7 is 1, and of 21 and 49 is 7. This is needed to simplify fractions for example. Explaining the maths that make the algorithm work is beyond the scope of this tutorial."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"> **Activity 10**\n",
|
|
">\n",
|
|
"> Translate the algorithm below to Python. One instruction was already translated for you. Don't forget to test your code."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Their greatest common divisor is 2\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# Euclid's greatest common divisor algorithm\n",
|
|
"\n",
|
|
"n = int(input(\"Enter an integer greater than zero (n): \"))\n",
|
|
"m = int(input(\"Enter another integer greater than zero (m): \"))\n",
|
|
"\n",
|
|
"while n != m:\n",
|
|
" if n > m:\n",
|
|
" n = n - m\n",
|
|
" else:\n",
|
|
" m = m - n\n",
|
|
"\n",
|
|
"print(\"Their greatest common divisor is\", n)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Note that for the loop to end, the condition must be false, i.e. both variables n and m have the same value. There it doesn't matter which one you print."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Summary"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In this brief introduction to programming you have seen the fundamental building blocks that almost every programming language provides:\n",
|
|
"\n",
|
|
"- variables and assignment (=) to store and update data\n",
|
|
"- arithmetic operators (+, -, *)\n",
|
|
"- simple data types (strings and numbers, both integers and floating point)\n",
|
|
"- data structures (lists)\n",
|
|
"- sequence (one instruction per line)\n",
|
|
"- iteration (for and while loops)\n",
|
|
"- selection (if-else and if-elif-elif-...-else),\n",
|
|
"- comparisons (>, <, ==, !=, >=, <=)\n",
|
|
"- functions (len and sum for lists, int and float to convert strings to numbers)\n",
|
|
"- input from the keyboard (input function)\n",
|
|
"- output to the screen (print instruction)\n",
|
|
"\n",
|
|
"Programming languages have to be automatically understood by a machine, so the syntax and grammar are much more constrained than English and other natural languages. Any spelling mistake, like writing flat instead of float or forgetting punctuation like commas and colons, or using the wrong data type, leads to an error.\n",
|
|
"\n",
|
|
"You have also seen that programming involves writing clear and understandable code (e.g. by using comments and plain English names for variables and functions) to make it easier to change later, and testing it thoroughly.\n",
|
|
"\n",
|
|
"Learning to program forces us to think clearly and rigorously when solving a problem, because the solution has to be described in very small and precise steps that even a machine can understand. Python makes it easy to write the code once we come up with a sufficiently detailed algorithm, but the thinking (still) has to be done by us.\n",
|
|
"\n",
|
|
"Like learning any other skill, only practice makes perfect. We hope this course inspired you to learn more Python and to share your creations with friends and family."
|
|
]
|
|
}
|
|
],
|
|
"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.12.4"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 2
|
|
}
|