3. Flow Control

About this Tutorial –

Objectives –

Python is a powerful and popular object-oriented scripting language. This course provides a comprehensive introduction to the core syntax and functions provided by Python, including full coverage of its object-oriented features. The course also explores some of Python’s powerful APIs and techniques, including file handling, XML processing, object serialization, and Web service

Audience

This training course is aimed at new developers and experienced developers

Prerequisites

No previous experience in Python programming is required. But any experience you do have in programming will help. Also no experience in IDLE is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The python course covers these topics and more:

  • Strings and Regular Expressions: Overview of strings in Python; Basic string manipulation; Introduction to regular expressions
  • XML Processing: XML essentials; Parsing XML documents; Searching for XML content; Generating XML data
  • Web Services: Overview of Web services; Implementing Web services using Python; Caching; Compression; Handling redirects

Download Solutions

HTML tutorial

Quick Access


Overview

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Functions

Lab 1: Conditional statements

Lab 1: Conditional statements
  1. Using if Tests
    • Basic if tests
      if expression :
       body
    • if-else tests
      if expression :
       body1
      else:
       body2
    • if-elif tests
      if expression1 :
       body1
      elif expression2 :
       body2
      elif expression3 :
       body3
      ...
      else :
       lastBody
    • Note the following points:
      • Python uses indentation to indicate the extent of the body in if tests, loops, functions, etc. Don’t try to use {}, they won’t work!
      • In Python, elif is a single keyword. This is different from a lot of other languages.
      • Put a : character at the end of the if / elif / else constructs, to indicate the start of a block.
      • The test condition does not need to be a boolean expression. For example, it could be a number, a string, etc. Python will automatically deduce truth or falsehood based on the value (e.g. a zero number or an empty string evaluates to false).
      • The test condition doesn’t need to be enclosed in parentheses.
  2. Nesting if Tests
    • You can nest if tests inside each other
      • Use indentation to indicate level of nesting
    • Here are some recommendations:
      • Be very careful with your indentation, because this will dictate the logical flow to the Python interpreter.
      • Don’t over do it. The code is already getting quite tricky. It might be a better idea to shovel some of this logic off into a separate function, to make your intentions clearer.
    • Example:
      age = int(input("Please enter your age: "))
      gender = input("Please enter your gender [M/F]: ").lower()
      if age < 18:  if gender == "m":   print("Boy")  else:   print("Girl") else:  if age >= 100:
        print("Centurion")
       if gender == "m":
        print("Man")
       else:
        print("Woman")
      print("The End")
    • View Code File

  3. Using the if-else Operator
    • The if-else operator is an in-situ test
      • trueResult if condition else falseResult
      • Example:
        isMale = ...
        age  = ...
        togo = (65 - age) if isMale else (60 - age)
        print("%d years to retirement" % togo)
      • View Code File

    • The if-else operator allows you to perform a test in a single expression. This is handy if you want to embed a decision inside another expression, as shown above:
      • You could achieve the same effect (less elegantly) using an if-else statement as follows
          isMale = ...
          age = ...
          if isMale:
            togo = 65 - age
          else:
            togo = 60 - age
          print("%d years to retirement" % togo)
  4. Doing Nothing
    • Sometimes in your programming logic, it’s convenient to define a null statement in response to a condition.
      • The way you do this in Python is by using the pass keyword.
    • Consider the example below. Presumably, we’re going to come back to this code later and add some programming logic to sort out the condition where the person’s favourite football team is Cardiff. You can use the pass keyword in several places in Python:
      • In a loop, to indicate no action during the loop.
      • In a function, to indicate an empty function body (i.e. you’re going to come back and implement the function later).
      • In a class, to indicate an empty class (ditto).
        team = input("Who is your favourite football team? ")
        if team == "Cardiff":
         pass   # Eeek. We'll need to do something about this!
        print("Your favourite team is %s " % team)
      • View Code File

  5. Testing a Value is in a Set of Values
    • A common task in programming is to test a value against a set of allowable values
      • In Python, you can achieve this very easily by using the in operator.
    • Example:
      • You supply the set of allowed values in parentheses, and Python will test if your variable is one of the specified values.
      • You can use this technique in many places where you might have written a switch statement in other languages.
        country = input("Please enter your country: ")
        if country in ("Netherlands", "Belgium", "Luxembourg"):
         print("Lowlands country")
        elif country in ("Norway", "Sweden", "Denmark", "Finland"):
         print("Nordic country")
        elif country in ("England", "Scotland", "Wales", "Northern Ireland"):
         print("UK country")
        else:
         print("%s isn't classified in this particular application!" % country)
      • View Code File

  6. Testing a Value is in a Range
    • You can test if a value is in a range of allowable values
      • The range() function returns a list of values from the start value to the end value.
      • The range includes the start value, but excludes the end value.
      • By default, the increment is 1.
    • Example:
      • range(2,6) – returns the list [2,3,4,5]
      • range(6,10) – returns the list [6,7,8,9]
        number = int(input("Enter a football jersey number [1 to 11]: "))
        if number == 1:
         print("Goalie")
        elif number in range(2, 6):
         print("Defender")
        elif number in range(6, 10):
         print("Midfielder")
        else:
         print("Striker")
      • View Code File

Lab
  1. Performing boolean operations
    • In the Student folder, open the dateprocessing.py module in the editor. The module contains some simple starter code, to ask the user to enter a day, month, and year. You will add various bits of code in this lab, to manipulate the date values
    • To start off, add some code to determine if the year is a leap year. A leap year is:
      • (evenly divisible by 4 and not evenly divisible by 100) or
      • (evenly divisible by 400)
      • Use the remainder operator (%) to help you out here
        isLeapYear = ((year % 4 == 0) and not(year % 100 == 0)) or (year % 400 == 0)
    • Print a message to indicate whether the year is a leap year. Then run the program several times, to test that your “is-leap-year” algorithm works for various years
      print("%02d/%02d/%04d isLeapYear? %s" % (day, month, year, isLeapYear))
  2. Using conditional logic
    • Validate the day, month, and year values. Output a single message saying whether the date is valid or not. Output it in the format dd/mm /yyyy
    • Suggestions and requirements:
      • The day must be 1…daysInMonth, where daysInMonth depends on the month and possibly the year. For example, there are 31 days in January, 28 or 29 days in February, and so on
        # Determine if it's a valid date
        if month == 2:
          daysInMonth = 29 if isLeapYear else 28
        elif month in (4, 6, 9, 11):
          daysInMonth = 30
        else:
          daysInMonth = 31
      • The month must be 1…12
      • The year must be 0-2099 (let’s say)
        isvalid = day >= 1 and day <= daysInMonth and \       month >= 1 and month <= 12 and \       year >= 0 and year <= 2099 print("%02d/%02d/%04d valid? %s" % (day, month, year, isvalid))
      • View Code File

    • Run the code and test it out by entering correct and incorrect data

Lab 2: Loops

Lab 2: Loops
  1. Using while Loops
    • The while loop is the most straightforward loop construct
      • Test expression is evaluated
      • If true, loop body is executed
      • Test expression is re-evaluated
      • Etc...
        while expression :
         loopBody
    • Note:
      • Loop body will not be executed if test is false initially
    • How would you write a while loop...
      • To display 1 - 5?
      • To display the first 5 odd numbers?
      • To read 5 strings from the console, and output in uppercase?
    • View Code File

  2. Using for Loops
    • For loops are a bit different in Python than in other languages
      • Rather than explicitly setting a loop control variable, testing it, and updating it on each iteration...
      • Python for loops iterate over the items of a sequence (e.g. a list, a string, or a range)
        for item in sequence :
         loopBody
    • Example
      lottonumbers = [2, 7, 3, 12, 19, 1]
      for item in lottonumbers:
       print(item)
    • View Code File

  3. Using for Loops with a Range
    • If you want to implement a "traditional for loop", starting at a certain number and iterating up to an end number
      • You can use the range() function to create the range of numbers you want to iterate over
    • The examples below shows three usages of the range() function:
      • The first example calls range() with a single parameter, specifying the exclusive upper bound. The inclusive lower bound is assumed to be 0, and the default increment size is 1. Therefore, this example prints the following numbers:
        0 1 2 3 4
      • The second example calls range() with two parameters, specifying the inclusive lower bound and the exclusive upper bound. The default increment size is 1 again. Therefore, this example prints the following numbers:
        6 7 8 9 10
      • The third example calls range() with three parameters, specifying the inclusive lower bound, the exclusive upper bound, and the increment size. Therefore, this example prints the following numbers:
        1 3 5 7 9
      • View Code File

  4. Unconditional Jumps
    • Python provides two ways to perform an unconditional jump in a loop
      • break
      • continue
    • The break statement terminates a loop immediately. This is useful if you decide you've found the record you were looking for, or if something has gone horribly wrong and there's no point carrying on with the loop.
    • The continue statement abandons the current loop iteration, and resumes at the top of the loop ready for the next iteration. This is useful if you decide the current record is invalid or irrelevant, and you want to skip it and move on to the next record.
    • Example:
      magicnumber = int(input("What is the magic number? "))
      print("This loop terminates if it hits the magic number")
      for i in range(1, 21):
       if i == magicnumber:
        break
       print(i)
      print("End")
      print("\nThis loop skips the magic number")
      for i in range(1, 21):
       if i == magicnumber:
        continue
       print(i)
      print("End")
    • View Code File

    • Note the following points in the example:
      • The first loop stops as soon as it hits the magic number entered by the user.
      • The second loop skips over the magic number and continues iteration on the next value in the sequence.
  5. Using else in a Loop
    • You can define an else clause at the end of a loop
      • Same kind of syntax as if...else
      • The else branch is executed if the loop terminates naturally (i.e. if it didn't exit because of a break)
    • This is quite useful if you're looping over a sequence of items, looking for a particular value in the sequence.
      • If you find it, you do some processing, and then break out of the loop
      • If you reach the end of the loop without finding the value you were looking for, then the else clause will be executed.
      • This is a good place to do something like displaying a message to the user, indicating the desired value wasn't found.
    • Example:
      magicnumber = int(input("What is the magic number? "))
      print("This loop does some processing if it doesn't detect the magic number")
      for i in range(1, 21):
       if i == magicnumber:
        break
       print(i)
      else:
       print("The magic number %d was not detected" % magicnumber)
      print("End")
    • View Code File

  6. Simulating do-while Loops
    • Many languages have a do-while loop
      • Guarantees at least one iteration through the loop body
      • The test is at the end, to determine whether to repeat
    • Python doesn't have a do-while loop, but you can emulate it as follows
      while True:
       exammark = int(input("Enter a valid exam mark: "))
       if exammark >= 0 and exammark <= 100:   break print("Your exam mark is %d" % exammark)
    • View Code File

    • The example shows how to simulate a do-while loop in Python. Note the following points:
      • The while loop will continue indefinitely (until it hits a break statement, of course).
      • The loop body executes at least once. In this example, it asks the user to enter a valid exam mark (i.e. between 0 and 100 inclusive).
      • If the exam mark is valid, it hits the break statement and the loop terminates. Otherwise the loop repeats, and asks the user to enter a valid exam mark again.
Lab
  1. Using loops
    • Add some code to display all the dates for a specific month (taking into account the number of days in that month, and whether or not it's February in a leap year), this will also include ensuring the the month is displayed as a string and a suffix is given for each date. For example, here's the output for February in 2016 (which is a leap year):
      1 st Februray 2016
      2 nd Februray 2016
      3 rd Februray 2016
      4 th Februray 2016
      ...
    • First thing you are going to need is something that will take the month number and turn it into a string - Hence we will use an if function for this
      # Determine the name of the month.    
      if month == 1:
        monthName = "January"
      elif month == 2:
        monthName = "February"
      elif month == 3:
        monthName = "March"
      elif month == 4:
      ...
      elif month == 10:
        monthName = "October"
      elif month == 11:
        monthName = "November"
      elif month == 12:
        monthName = "December"
      else:
        monthName = "Not Known"   # Should never happen
    • View Code File

    • Then we need to create code that will loop through all the days and will give them the correct suffix; this can also be done using an if function, but this time it will be nested in a for loop:
      # Display all the dates in the month.
      print("Dates in %s, %d" % (monthName, year))
      for day in range(1, daysInMonth+1):
        if day in (1, 21, 31):
          suffix = "st"
        elif day in (2, 22):
          suffix = "nd"
        elif day in (3, 23):
          suffix = "rd"
        else:
          suffix = "th"
        print("%d%s %s %d" % (day , suffix, monthName, year))
    • View Code File

    • As usual run this code using F5 and make sure everything is working

 

Well done. You have completed the tutorial in the Python course. The next tutorial is

4. Functions


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top