{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import time\n", "import sys\n", "import random" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python \n", "\n", "# [Control Flow Commands](https://docs.python.org/3/tutorial/controlflow.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "+ _if_ , _elif_, _else_\n", "+ _for_\n", "+ _while_\n", "+ _break_, _continue_, _pass_\n", "+ _try_, _except_, _else_, _finally_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditional: _if_ / _elif_ / _else_\n", "\n", "+ Python uses the control flow if/elif/else to evaluate expressions \n", "+ Conditions can be evaluated as True or False \n", "+ One block can contain one _if_ statement, zero, one or many _elif_ statements and zero or one _else_ statement. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sintax:\n", "\n", " if : \n", " code \n", " elif : (optional) \n", " code \n", " elif : (optional) \n", " code \n", " ... \n", " else: (optional) \n", " code \n", " \n", "### [Conditional Expression]() (Ternary Operator)\n", "\n", " if else " ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Name does not start with T,U,V, X or Z\n", "Ending if statement\n" ] } ], "source": [ "name = 'Matheus'\n", "\n", "if name.startswith('T'):\n", " print(f'Name starts with {name[0]}')\n", " print('I am here')\n", "elif name.startswith('U'):\n", " print(f'Name starts with {name[0]} and ends with {name[-1]}')\n", "elif name.startswith('V'):\n", " print(f'Name starts with {name[0]}')\n", "elif name.startswith('X'):\n", " print(f'Name starts with {name[0]}')\n", "elif name.startswith('Z'):\n", " print(f'Name starts with {name[0]}')\n", "else:\n", " print('Name does not start with T,U,V, X or Z')\n", "\n", "print('Ending if statement')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Nested _if_ statements" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "the number is less or equal to 5\n" ] } ], "source": [ "number = 4\n", "if number > 5:\n", " print('greater than 5')\n", " if number > 7:\n", " print('greater than 7')\n", " else:\n", " print('lower or equal than 7')\n", " if number > 3:\n", " print('greater than 3')\n", "else:\n", " print('the number is less or equal to 5')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### if, with ternary operator" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "done\n" ] } ], "source": [ "x = \"do that\"\n", "if x == \"do that\":\n", " print(\"done\")\n", "else:\n", " print('not done')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "done\n" ] } ], "source": [ "print(\"done\") if x == \"do that\" else print(\"not done\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loops: the _for_ command" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "+ _for_ takes a sequence and loops through it, until it ends\n", "+ Each pass is called an _iteration_\n", "+ Any object that is _iterable_ can be passed to _for_ loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Sintax:\n", "\n", " for in :\n", " code" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "---\n", "2 Daysies\n", "\n", "---\n", "6 Daysies\n", "\n", "---\n", "10 Daysies\n", "\n" ] } ], "source": [ "for integer in range(2,11,4):\n", " print('---')\n", " print(f'{integer} Daysies')\n", " print()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "9\n", "25\n", "49\n", "81\n" ] } ], "source": [ "for number in range(1,10,2):\n", " print(number**2)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "M\n", "n\n", "e\n", "s\n", "i\n", "l\n", "J\n", "n\n" ] } ], "source": [ "for letter in 'My name is Little John'[::3]:\n", " print(letter)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 1 1\n", "4 16 64\n", "8 64 512\n", "9 81 729\n", "10 100 1000\n" ] } ], "source": [ "for element in [1,4,8,9,10]:\n", " print(element, element**2, element**3)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "4\n", "5\n" ] } ], "source": [ "c = {1,4,4,4,4,5}\n", "for element in c:\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "k1\n", "k2\n" ] } ], "source": [ "d = {\"k1\":1,\"k2\":2}\n", "for element in d:\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loop with conditional: the comman _while_\n", "\n", "+ With _while_, you define a condition at the beggining\n", "+ While the condition is true, the loop will continue\n", "+ It is easy to create infinite loops with _while_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Sintax:\n", "\n", " while :\n", " code" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "x = 1\n", "while x < 10:\n", " print(x)\n", " x += 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Change flow behaviour with _break_, _continue_ and _pass_\n", "\n", "+ The _break_ statement, breaks out of the innermost enclosing for or while loop.\n", "+ The _continue_ statement continues with the next iteration of the loop.\n", "+ The _pass_ statement does nothing. It can be used when a statement is required syntactically but the program requires no action." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "+ ### break" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "m\n", "y\n", " \n", "t\n" ] } ], "source": [ "for letter in \"my text is not long\":\n", " print(letter)\n", " if letter == \"t\":\n", " break" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "10\n" ] } ], "source": [ "x = 0\n", "while True:\n", " print(x)\n", " x += 1\n", " if x > 10:\n", " break" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sum of first 120 integers is : 7260\n" ] } ], "source": [ "numbers = range(1,1000)\n", "num_sum = 0 \n", "count = 0 \n", "\n", "for x in numbers: \n", " num_sum += x # num_sum = num_sum + x\n", " count += 1 # count = count + 1\n", " if count == 120: \n", " break \n", "print(f\"Sum of first {count} integers is : {num_sum}\") " ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.39390491311022113\n", "0.02059721074073162\n", "0.3680639202086302\n", "0.047432914561115425\n", "0.525620157158587\n", "0.0541643504168946\n", "0.833944933582663\n", "0.500141408809124\n", "0.9244719453643567\n", "0.6077280816290723\n", "0.5688913683007965\n", "0.9065592659222461\n", "0.5945998832589053\n", "0.8063098111105633\n", "0.7244928880971366\n", "0.20385087654041423\n", "0.0654796682469061\n", "0.5092596047807845\n", "0.7676337916247657\n", "0.5315098386841017\n", "0.6775850045834193\n", "0.28953569483384733\n", "0.47090595606458807\n" ] } ], "source": [ "while True:\n", " x = random.random()\n", " print(x)\n", " if 0.5 > x > 0.4:\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "+ ### continue" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "6\n", "8\n" ] } ], "source": [ "for number in range(10):\n", " if number in [5,7,9]:\n", " continue\n", " print(number)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x equals to 1 and y equals to 2\n", "x equals to 7 and y equals to 9\n", "x equals to 1 and y equals to 7\n" ] } ], "source": [ "for x,y in [(1,2),(3,6),(7,9),(3,4),(1,7)]:\n", " if x == 3:\n", " continue\n", " print(f'x equals to {x} and y equals to {y}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "+ ### pass" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "unexpected EOF while parsing (1901971030.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Input \u001b[0;32mIn [19]\u001b[0;36m\u001b[0m\n\u001b[0;31m for x in range(10): #error\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unexpected EOF while parsing\n" ] } ], "source": [ "for x in range(10): #error" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "for x in range(10):\n", " pass" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Current Letter : P\n", "Current Letter : y\n", "Current Letter : t\n", "This is a pass block\n", "Current Letter : h\n", "Current Letter : o\n", "Current Letter : n\n" ] } ], "source": [ "for letter in 'Python': \n", " if letter == 'h':\n", " pass\n", " print('This is a pass block')\n", " print('Current Letter :', letter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### _try_, _except_, _else_, _finally_, _raise_ \n", "\n", "[Exception types in Python](https://docs.python.org/3/tutorial/errors.html) \n", "See also: [this](https://stackabuse.com/python-exception-handling/)\n", "\n", "+ _try_ lets you handle errors/exceptions in the code. \n", "+ _except_ lets you take an action with this occurs. \n", "+ _else_ lets you take an action when no error occurs. \n", "+ _finally_ Lets you take an action no matter if errors ocurred or not. \n", "+ _raise_ Allows the programmer to force a specified exception to occur." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Python Exceptions" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "linux\n" ] } ], "source": [ "print(sys.platform)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "ename": "AssertionError", "evalue": "This code runs on Linux only.", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [23]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m (\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mwindows\u001b[39m\u001b[38;5;124m'\u001b[39m \u001b[38;5;129;01min\u001b[39;00m sys\u001b[38;5;241m.\u001b[39mplatform), \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mThis code runs on Linux only.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n", "\u001b[0;31mAssertionError\u001b[0m: This code runs on Linux only." ] } ], "source": [ "assert ('windows' in sys.platform), \"This code runs on Linux only.\"\n", "#assert ('linux' in sys.platform), \"This code runs on Linux only.\"" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'file.log'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [24]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mopen\u001b[39m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mfile.log\u001b[39m\u001b[38;5;124m'\u001b[39m) \u001b[38;5;28;01mas\u001b[39;00m my_file: \u001b[38;5;66;03m# error\u001b[39;00m\n\u001b[1;32m 2\u001b[0m read_data \u001b[38;5;241m=\u001b[39m my_file\u001b[38;5;241m.\u001b[39mread()\n", "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'file.log'" ] } ], "source": [ "with open('file.log') as my_file: # error\n", " read_data = my_file.read()" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Could not open file.log\n" ] } ], "source": [ "try:\n", " with open('file.log') as my_file:\n", " read_data = my_file.read()\n", "except:\n", " print('Could not open file.log')" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'int' and 'list'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [26]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m x \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m2\u001b[39m\n\u001b[1;32m 2\u001b[0m y \u001b[38;5;241m=\u001b[39m [\u001b[38;5;241m1\u001b[39m,\u001b[38;5;241m3\u001b[39m]\n\u001b[0;32m----> 3\u001b[0m x \u001b[38;5;241m+\u001b[39m y\n", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'list'" ] } ], "source": [ "x = 2\n", "y = [1,3]\n", "x + y # error" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "An error has occurred with summing two variables\n" ] } ], "source": [ "try:\n", " x + y \n", "except:\n", " print(\"An error has occurred with summing two variables\")" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Everythink is ok\n" ] } ], "source": [ "x,y = 2,3\n", "\n", "try:\n", " x + y \n", "except:\n", " print(\"An error has occurred\")\n", "else:\n", " print(\"Everythink is ok\")" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Everythink is ok\n", "Ending try/except block\n" ] } ], "source": [ "try:\n", " x + y \n", "except:\n", " print(\"An error has occurred\")\n", "else:\n", " print(\"Everythink is ok\")\n", "finally:\n", " print(\"Ending try/except block\")" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "try:\n", " x + y \n", "except Exception as error:\n", " print(type(error))\n", " print(f\"Exception caught: {error}\")" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Type Error\n" ] } ], "source": [ "try:\n", " x + [y] \n", "except TypeError:\n", " print(\"Type Error\")\n", "except ValueError:\n", " print(\"Value Error\") \n", "except Exception as e:\n", " print(\"Exception caught:\" + str(e))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sintax Errors cannot be captured with try. See [this](https://stackoverflow.com/questions/25049498/failed-to-catch-syntax-error-python) post" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I/O error(2): No such file or directory\n" ] } ], "source": [ "try:\n", " f = open('integers.txt')\n", " s = f.readline()\n", " i = int(s.strip())\n", "except IOError as e:\n", " errno, strerror = e.args\n", " print(\"I/O error({0}): {1}\".format(errno, strerror))\n", " # e can be printed directly without using .args:\n", " # print(e)\n", "except ValueError:\n", " print(\"No valid integer in line.\")\n", "except Exception as e:\n", " print(\"Exception caught:\" + str(e))\n", " raise" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.8.10" } }, "nbformat": 4, "nbformat_minor": 4 }