{ "metadata": { "name": "Chapter3_Control_flow" }, "nbformat": 3, "nbformat_minor": 0, "orig_nbformat": 2, "worksheets": [ { "cells": [ { "cell_type": "markdown", "source": [ "[Python for Developers](http://ricardoduarte.github.io/python-for-developers/#content)\n", "===================================\n", "First edition\n", "-----------------------------------\n", "\n", "Chapter 3: Control Flow\n", "=============================\n", "_____________________________\n", "It is very common for a program that certain sets of instructions are executed conditionally, in cases such as validating data entries, for example.\n", "\n", "Syntax:\n", "\n", " if :\n", " \n", " elif :\n", " \n", " elif :\n", " \n", " else:\n", " \n", "\n", "Where:\n", "\n", "+ ``: sentence that can be evaluated as true or false.\n", "+ ``: sequence of command lines.\n", "+ The clauses `elif` and `else` are optional and\u00a0 several `elifs` for the `if` may be used but only\u00a0 one `else` at the end.\n", "+ Parentheses are only required to avoid ambiguity.\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "temp = 23 # temperature value used to test\n", "\n", "if temp < 0:\n", " print 'Freezing...'\n", "elif 0 <= temp <= 20:\n", " print 'Cold'\n", "elif 21 <= temp <= 25:\n", " print 'Normal'\n", "elif 26 <= temp <= 35:\n", " print 'Hot'\n", "else:\n", " print 'Very Hot!'" ], "language": "python", "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Normal\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "source": [ "Imagine that in the above program, `23` is the temperature which was read by\u00a0 some sensor or manually entered by the user and `Normal` is the response of the program.\n", "\n", "If the code block is composed of only one line, it can be written after the colon:\n", "\n", " if temp < 0: print 'Freezing...'\n", "\n", "Since version 2.5, Python supports the expression:\n", "\n", " = if else \n", "\n", "Where `` receives `` if `` is true and `` otherwise." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "outputs": [ { "html": [ "\n", "" ], "output_type": "pyout", "prompt_number": 1, "text": [ "" ] } ], "prompt_number": 1 } ] } ] }