{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lecture 1: Python introduction" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Compiled and interpreted languages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are two major categories of programming languages: **compiled and interpreted**.\n", " * A compiled language is a language that is turned by a compiler into direct machine code that runs upon the CPU. (Or it might run on a virtual machine stack like the JavaVM or the .NET runtime.)\n", " * An interpreted language is a language that is read in its raw form and executed a statement at a time without being first compiled.\n", "\n", "**Python is an interpreted langauge.**\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How Jupyter Notebook works" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A notebook contains cells, each cell is a logically separate and independent information.\n", "\n", "There are 2 main type of cells:\n", "* Markdown cells\n", " * Write documentation and comments\n", " * Can be formatted with *markdown* syntax\n", " * [See this tutorial on how to use markdown](https://guides.github.com/features/mastering-markdown/)\n", "* Code cells\n", " * Write code\n", " * Evaluate code on the fly\n", "\n", "Note: you can find a *User interface tour* in the *Help* menu." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "# Let's get Python started! Hello world!\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Literals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Literals are constans primitive values. They can be e.g. numbers or strings (texts). Strings are surrounded with quotation marks or apostrophes." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"Hello World\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'Hello Earth'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "42" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Print" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Syntax: `print` is a function, which has an argument. The argument is surrounded by parentheses.\n", " * The argument can be a string literal between quotation\n", " * Or a number literal\n", " * Or a variable" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('Hello World')\n", "print(\"Hello Earth\")\n", "print(4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Task:** what is the problem with the following codes?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(Hello ELTE!)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print \"Hello IK!\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Handling outer Python files" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Viewing the content of an external file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can load the content of an externak file with the special `%load` command:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# %load 01_outerfile.py\n", "print('Great! This line was print from an external file!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Executing an external file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Specifying the `-i` flag is important, so the file is executed in the same environment with the Jupyter notebook. Therefore if we e.g. declare a variable in the external script, it will be accessible in the code cells of the notebook.\n", "If the `-i` flag is not specified, the external Python file is evaluated in a separate environment." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%run -i 01_outerfile.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Vairables can be considered __containers__. You can put anything inside a container, __without specifying the size or type__, which will be needed in Java or C. Note that Python is case-sensitive. Be careful about using letters in different cases." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When assigning values, we put the variable to be assigned to on the left hand side (LHS), while the value to plug in on the RHS. LHS and RHS are connected by an equal sign (`=`), meaning assignment." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2017-10-04T18:38:12.552928Z", "start_time": "2017-10-04T18:38:12.543725Z" } }, "outputs": [], "source": [ "x = 3 # integer\n", "y = 3. # floating point number\n", "z = \"Hello!\" # strings\n", "Z = \"Wonderful!\" # another string, stored in a variable big z.\n", "print(x)\n", "print(y)\n", "print(z)\n", "print(Z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can do operations on numeric values as well as strings." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:38:17.443096Z", "start_time": "2018-10-09T01:38:17.439036Z" } }, "outputs": [], "source": [ "sum_ = x + y # int + float = float\n", "print(sum_)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2017-10-04T18:38:13.972732Z", "start_time": "2017-10-04T18:38:13.967236Z" } }, "outputs": [], "source": [ "v = \"World!\"\n", "sum_string = z + \" \" + v # concatenate strings\n", "print(sum_string)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Print with formating with `%`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2017-10-04T18:38:15.178277Z", "start_time": "2017-10-04T18:38:15.173368Z" } }, "outputs": [], "source": [ "print(\"The sum of x and y is %.2f\" % sum_) # %f for floating point number" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2017-10-04T18:38:15.472965Z", "start_time": "2017-10-04T18:38:15.467306Z" } }, "outputs": [], "source": [ "print(\"The string `sum_string` is '%s'\" % sum_string) # %s for string" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Naming convention" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are two commonly used style in programming:\n", "\n", "1. __camelCase__\n", "2. __snake_case__ or __lower_case_with_underscore__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All variable (function and class) names must start with a letter or underscore (\\_). You can include numbers." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:28.497486Z", "start_time": "2018-10-09T00:16:28.491966Z" } }, "outputs": [], "source": [ "myStringHere = 'my string'\n", "myStringHere" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:28.879472Z", "start_time": "2018-10-09T00:16:28.875812Z" } }, "outputs": [], "source": [ "x = 3 # valid\n", "x_3 = \"xyz\" # valid" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:29.096887Z", "start_time": "2018-10-09T00:16:29.091476Z" } }, "outputs": [], "source": [ "3_x = \"456\" # invalid. Numbers cannot be in the first position." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can choose either camel case or snake case. Always make sure you use one convention consistenly across one project." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Some notes on Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To initialize a string variable, you can use either double or single quotes." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:32.520585Z", "start_time": "2018-10-09T00:16:32.516838Z" } }, "outputs": [], "source": [ "store_name = \"Hello World!\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can think of strings as a sequence of characters (or a __list__ of characters, which we will cover later). In this case, indices and bracket notations can be used to access specific ranges of characters." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:32.814921Z", "start_time": "2018-10-09T00:16:32.811324Z" } }, "outputs": [], "source": [ "name_13 = store_name[1:4] # [start, end), end is exclusive; Python starts with 0 NOT 1\n", "print(name_13)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:33.080003Z", "start_time": "2018-10-09T00:16:33.075926Z" } }, "outputs": [], "source": [ "last_letter = store_name[-1] # -1 means the last element\n", "print(last_letter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Simple Data Structures" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this section, we go over some common primitive data types in Python. While the word _primitive_ looks obscure, we can think of it as the most basic data type that cannot be further decomposed into simpler ones." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For numbers without fractional parts, we say they are ___integer___. In Python, they are called `int`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-08T23:51:10.632494Z", "start_time": "2018-10-08T23:51:10.598421Z" } }, "outputs": [], "source": [ "x = 3\n", "type(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For numbers with fractional parts, they are floating point numbers. They are named `float` in Python." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-08T23:51:54.013974Z", "start_time": "2018-10-08T23:51:54.008407Z" } }, "outputs": [], "source": [ "y = 3.0\n", "type(y)" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2018-10-08T23:55:03.134594Z", "start_time": "2018-10-08T23:55:03.118103Z" } }, "source": [ "We can apply arithmetic to these numbers. However, one thing we need to be careful about is ___type conversion___. See the example below." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-08T23:55:31.855870Z", "start_time": "2018-10-08T23:55:31.847879Z" } }, "outputs": [], "source": [ "z = 2 * x\n", "type(z)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-08T23:55:36.207707Z", "start_time": "2018-10-08T23:55:36.202449Z" } }, "outputs": [], "source": [ "z = y + x\n", "type(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Text/Characters/Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Python, we use `str` type for storing letters, words, and any other characters." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-08T23:57:26.831211Z", "start_time": "2018-10-08T23:57:26.826020Z" } }, "outputs": [], "source": [ "my_word = \"see you\"\n", "type(my_word)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Unlike numbers, `str` is an iterable object, meaning that we can iterate through each individual character:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-08T23:58:44.058368Z", "start_time": "2018-10-08T23:58:44.052694Z" } }, "outputs": [], "source": [ "my_word[0], my_word[2:6]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use `+` to _concatenate_ different strings " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-08T23:59:16.399980Z", "start_time": "2018-10-08T23:59:16.395030Z" } }, "outputs": [], "source": [ "my_word + ' tomorrow'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Boolean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Boolean type comes in handy when we need to check conditions. For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:00:33.751846Z", "start_time": "2018-10-09T00:00:33.746658Z" } }, "outputs": [], "source": [ "my_error = 1.6\n", "compare_result = my_error < 0.1\n", "compare_result, type(compare_result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are two and only two valid Boolean values: `True` and `False`. We can also think of them as `1` and `0`, respectively." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:02:30.834630Z", "start_time": "2018-10-09T00:02:30.830339Z" } }, "outputs": [], "source": [ "my_error > 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we use Boolean values for arithmetic operations, they will become `1 / 0` automatically" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:02:52.791120Z", "start_time": "2018-10-09T00:02:52.783315Z" } }, "outputs": [], "source": [ "(my_error>0) + 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Type Conversion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since variables in Python are dynamically typed, we need to be careful about type conversion." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When two variables share the same data type, there is not much to be worried about:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:04:59.077234Z", "start_time": "2018-10-09T00:04:59.072252Z" } }, "outputs": [], "source": [ "s1 = \"no problem. \"\n", "s2 = \"talk to you later\"\n", "s1 + s2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But be careful when we are mixing variables up:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:06:03.221806Z", "start_time": "2018-10-09T00:06:03.217855Z" } }, "outputs": [], "source": [ "a = 3 # recall that this is an ____?\n", "b = 2.7 # how about this?\n", "c = a + b # what is the type of `c`?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To make things work between string and numbers, we can explicitly convert numbers into `str`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:07:59.974061Z", "start_time": "2018-10-09T00:07:59.964373Z" } }, "outputs": [], "source": [ "s1 + 3" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:08:04.034457Z", "start_time": "2018-10-09T00:08:04.027842Z" } }, "outputs": [], "source": [ "s1 + str(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We may also convert string to numbers:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s3 = \"42\"\n", "d = int(s3)\n", "type(s3), type(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# User input" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "User input can be easily requested in Python:\n", "\n", "```python\n", "k=input('Question')\n", "```\n", "\n", "The question text is arbitrary. The user will see a console input prompt. The typed input will be stored in the `k` variable by Python. Example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "k=input('What is your name? ')\n", "print('Hello ' + k)\n", "type(k)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Task: Query the height of the user.**\n", "\n", "Print afterward that *Your height is XXX centimeter.*\n", "\n", "Print the type of the variable storing the height of the user." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "height=input(\"What is your height? \")\n", "print(\"Your height is %s centimeters.\" % height)\n", "print(type(height))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Variable assigned by the **input** function will always contains strings. (We will cover error handling later.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Basic operations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Mathematical operations are executed in an order as you get used to in mathmatics.\n", "\n", "See the [precedence order of all Python operators](https://docs.python.org/3/reference/expressions.html#operator-precedence) in the documentation. Operations with the same precedence are evaluated from left to right." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Both numeric and string values can be added together.\n", "\n", "For numeric values it works like the mathematical operation, e.g.: `1+2=3`.\n", "\n", "For string values they are concatenated, e.g.: `'Hello '+'world'='Hello world'`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(1+2)\n", "print('Hello '+'world')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x=10\n", "y=20\n", "print(x+y)\n", "\n", "z='10'\n", "q='20'\n", "print(z+q)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Substraction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Works only for numeric values:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(10-7)\n", "\n", "x=20\n", "print(x-10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiplication" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The multiplication operator can be applied both between 2 numeric values and between a string and a numeric value.\n", "\n", "For numeric values it works like the mathematical operation, e.g.: `9*4=36`.\n", "\n", "For a string and an integer, the string is repeated and concatenated as many times as we defined, e.g.: `'Hi'*5=HiHiHiHiHi`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(9*4)\n", "print('Hi'*5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x=9\n", "y=x*4\n", "print(y)\n", "\n", "z='Hi'\n", "w=z*5\n", "print(w)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Division with floating result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Works only for numeric values." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(17/3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question:** what is the type of the divident and the divisor? What is the type of the result?\n", "\n", "**Question:** what will be the type of the result if the value is an integer?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(type(17))\n", "print(type(3))\n", "print(type(17/3))\n", "print(type(18/3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Division with integer result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the double division operator (`//`) means that the result of the divison will be an integer number.\n", "If the result has a fractional part, it is dropped." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(18//3)\n", "print(17//3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exponentiation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can calculate the *yth* power of *x* by using the double star (`*`) operator: `x**y`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(2**3)\n", "\n", "x=3\n", "y=4\n", "print(x**y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Remainder (modulo operator)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In computing, the *modulo operation* finds the remainder after division of one number by another (called the *modulus* of the operation).\n", "\n", "E.g. `17%3=2`, since 15 is divisable by 3 and the remainder is therefore 2.\n", "\n", "Useful scenarios:\n", " * check whether a number is divisable by another (the modulus must be 0);\n", " * get the last digit of a number by calculating the remainder by 10." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "print(17%3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Summary exercise on data types, operations and user input" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Task: Calculate the distance between two 3D points.**\n", "\n", "Ask the user to input the coordinates of two 3 dimensional points (*x*, *y*, *z*).\n", "\n", "Calculate their distance in the 3 dimensional space and print it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "p1_x = float(input(\"P1.X := \"))\n", "p1_y = float(input(\"P1.Y := \"))\n", "p1_z = float(input(\"P1.Z := \"))\n", "p2_x = float(input(\"P2.X := \"))\n", "p2_y = float(input(\"P2.Y := \"))\n", "p2_z = float(input(\"P2.Z := \"))\n", "\n", "distance = ((p1_x-p2_x)**2 + (p1_y-p2_y)**2 + (p1_z-p2_z)**2) ** 0.5\n", "print(\"Distance(P1, P2) = %.2f\" % distance)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Control Logics" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are 3 basic control flows for all *imperative* programming languages: **sequences**, **conditions** and **loops**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sequence" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When operations are evaluated seqentially one after another, it is called a *sequence statement*." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"First statement\")\n", "print(\"Second statement\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Conditions (or also called *select statements*):\n", " * define multiple branches of the program code;\n", " * it is decided based on logical tests that which branch should be executed." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:38:46.027739Z", "start_time": "2018-10-09T01:38:46.023274Z" } }, "outputs": [], "source": [ "sum_" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:38:47.709640Z", "start_time": "2018-10-09T01:38:47.704307Z" } }, "outputs": [], "source": [ "if sum_ == 0:\n", " print(\"sum_ is 0\")\n", "elif sum_ < 0:\n", " print(\"sum_ is less than 0\")\n", "else:\n", " print(\"sum_ is above 0 and its value is \" + str(sum_)) # Cast sum_ into string type." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that you do not have to use `if-else` or `if-elif-...-else`. You can use `if` without other clauses following that." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:38:49.218876Z", "start_time": "2018-10-09T01:38:49.214871Z" } }, "outputs": [], "source": [ "if sum_ > 5:\n", " print('sum_ is above 5')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Comparing strings are similar:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:38:50.755605Z", "start_time": "2018-10-09T01:38:50.751523Z" } }, "outputs": [], "source": [ "store_name = 'Auchan'\n", "#store_name = 'Tesco'" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:38:57.568568Z", "start_time": "2018-10-09T01:38:57.563726Z" } }, "outputs": [], "source": [ "if store_name == 'Auchan':\n", " print(\"The store is an Auchan.\")\n", "else:\n", " print(\"The store is not an Auchan. It's \" + store_name + \".\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**IMPORTANT:** the indentation of the code is crucial, because it defines the code blocks!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if store_name == 'Tesco':\n", " print(\"The store is a Tesco. Line 1.\")\n", " print(\"The store is a Tesco. Line 2.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if store_name == 'Tesco':\n", " print(\"The store is a Tesco. Line 1.\")\n", "print(\"The store is a Tesco. Line 2.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Some notes on comparison" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python syntax for comparison is the same as our hand-written convention: \n", "\n", "1. Larger (or equal): `>` (`>=`)\n", "2. Smaller (or equal): `<` (`<=`)\n", "3. Equal to: `==` (__Note here that there are double equal signs__)\n", "4. Not equal to: `!=`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:20.683160Z", "start_time": "2018-10-09T00:16:20.676171Z" } }, "outputs": [], "source": [ "3 == 5 " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:21.107023Z", "start_time": "2018-10-09T00:16:21.102607Z" } }, "outputs": [], "source": [ "72 >= 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:49.169393Z", "start_time": "2018-10-09T00:16:49.164386Z" } }, "outputs": [], "source": [ "store_name" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:16:49.460268Z", "start_time": "2018-10-09T00:16:49.453590Z" } }, "outputs": [], "source": [ "store_name == \"Tesco\" # Will return a boolean value True or False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**IMPORTANT:** Note that folating point precision and therefor comparisons between floating point numbers can be tricky." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:17:16.577984Z", "start_time": "2018-10-09T00:17:16.571556Z" } }, "outputs": [], "source": [ "print(2.2 * 3.0)\n", "2.2 * 3.0 == 6.6" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T00:17:16.777940Z", "start_time": "2018-10-09T00:17:16.771796Z" } }, "outputs": [], "source": [ "3.3 * 2.0 == 6.6" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The loop control flow is also called *iteration* or *repetition statement* and provides a way to execute the same code block (call the *core* of the iteration) until a condition is meet." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### for loop: Iterating through a sequence" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:39:07.309307Z", "start_time": "2018-10-09T01:39:07.305696Z" } }, "outputs": [], "source": [ "for letter in store_name:\n", " print(letter)" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2017-10-04T18:38:51.792543Z", "start_time": "2017-10-04T18:38:51.786228Z" } }, "source": [ "`range()` is a function to create integer sequences" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:41:05.935416Z", "start_time": "2018-10-09T01:41:05.930030Z" } }, "outputs": [], "source": [ "for index in range(len(store_name)): # length of a sequence\n", " print(\"The %ith letter in store_name is: %s\"%(index, store_name[index]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result of a `range()` function call is not list of all numbers in the range, but can be converted to it:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:41:03.662280Z", "start_time": "2018-10-09T01:41:03.657790Z" } }, "outputs": [], "source": [ "print(\"range(5) gives\" + str(list(range(5)))) # By default starts from 0\n", "print(\"range(1,9) gives: \" + str(list(range(1, 9)))) # From 1 to 9-1 (Again the end index is exclusive.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will cover *lists* in more detail later." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### While loop: Keep doing until condition no longer holds" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use `for` when you know __the exact number of iterations__; use `while` when you __do not (e.g., checking convergence)__." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:41:12.053207Z", "start_time": "2018-10-09T01:41:12.049347Z" } }, "outputs": [], "source": [ "x = 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:41:12.294825Z", "start_time": "2018-10-09T01:41:12.290846Z" } }, "outputs": [], "source": [ "while x < 10:\n", " print(x)\n", " x = x + (x-1)\n", " #x += x-1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Notes on `break` and `continue`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`break` means get out of the loop immediately. Any code after the `break` will NOT be executed." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:41:21.493159Z", "start_time": "2018-10-09T01:41:21.489747Z" } }, "outputs": [], "source": [ "store_name = 'Auchan'" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:41:22.084338Z", "start_time": "2018-10-09T01:41:22.076857Z" } }, "outputs": [], "source": [ "index = 0\n", "while True:\n", " print(store_name[index])\n", " index += 1 # a += b means a = a + b\n", " if store_name[index] == \"h\":\n", " print(\"End at h\")\n", " break # instead of setting flag to False, we can directly break out of the loop\n", " print(\"Hello!\") # This will NOT be run" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`continue` means get to the next iteration of loop. It will __break__ the current iteration and __continue__ to the next." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:41:23.822603Z", "start_time": "2018-10-09T01:41:23.818257Z" } }, "outputs": [], "source": [ "for letter in store_name:\n", " if letter == \"h\":\n", " continue # Not printing V\n", " else:\n", " print(letter)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2018-10-09T01:41:24.791324Z", "start_time": "2018-10-09T01:41:24.780078Z" } }, "outputs": [], "source": [ "index = 0\n", "while index <= len(store_name)-1:\n", " print(store_name[index])\n", " if store_name[index] == \"h\":\n", " print(\"This is an `h`\")\n", " index += 1 # a += b means a = a + b\n", " continue\n", " print(\"Hello!\") # This will NOT be run\n", " index += 1 # a += b means a = a + b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have already used (*called*) functions multiple times, like `print()`, `int()` or `len()`. These functions can:\n", " * accept 0, 1 or multiple parameters;\n", " * return a value or not;\n", " * meanwhile causing *side-effects*, like printing a message on the console output." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By defining custom functions, the redundancy in the code can be reduced. A custom function can be defined with the `def` keyword:\n", "```\n", "def function_name ( ):\n", " function_statement\n", "```\n", "\n", "For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def add(a, b):\n", " print(\"Adding %d and %d\" % (a,b))\n", " c = a + b\n", " return c\n", "\n", "result = add(10, 32)\n", "print(result)\n", "result = add(-5, 8)\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What will be the type of a function?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(type(add))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Functions returning a value are called *fruitful* functions. Functions without a return value are called *void* functions. In that case the returned value is *None*." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def greet(name):\n", " print(\"Hello %s!\" % name)\n", " \n", "greet(\"Matthew\")\n", "result = greet(\"Andrew\")\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Summary exercise for control logics" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Task: Test whether a number is a prime**\n", "\n", "Request an integer number from the user.\n", "\n", "Decide whether the number is a prime number or not and display your answer.\n", "\n", "*Optional:* create an `is_prime()` function which return a boolean value, whether the received parameter was a prime or not." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import math\n", "\n", "def is_prime(number):\n", " # Handle 0 and 1 as a special case\n", " if number < 2:\n", " return False\n", " \n", " # Numbers >= 2 are tested whether they have any divisors\n", " for i in range(2, int(math.sqrt(number) + 1)):\n", " #print(\"Testing divisor %d\" % i)\n", " if number % i == 0:\n", " # If we found a divisor, we can stop checking, because the number is NOT a prime\n", " return False\n", " \n", " # If no divisors were found, then the number is a prime\n", " return True\n", "\n", "try:\n", " num = int(input(\"Number to check: \"))\n", " if is_prime(num):\n", " print(\"%d is a prime\" % num)\n", " else:\n", " print(\"%d is NOT a prime\" % num)\n", "except:\n", " print(\"That was not a number!\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Homework exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Task: calculate the *greatest common divisor* of 2 numbers**\n", "\n", "Request 2 integer numbers from the user and calculate their greatest common divisor.\n", "\n", "E.g. for 30 and 105 their greatest common divisor is 15.\n", "\n", "*Tip: use the [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm)*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def gcd(a, b):\n", " while a != b:\n", " if a > b:\n", " a = a -b\n", " elif a < b:\n", " b = b - a\n", " return a\n", "\n", "try:\n", " first = abs(int(input(\"First number: \")))\n", " second = abs(int(input(\"Second number: \")))\n", " divisor = gcd(first, second)\n", " print(\"Greatest common divisor: %d\" % divisor)\n", "except:\n", " print(\"Both numbers must be integers!\")" ] } ], "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 }