Session 5

• Creating and using subroutines

Introduction (5 mins)

  • Using slide 2, ask participants what they think the code does.

  • Participants should do level 61. NB Some participants will not have used subroutines before so you will need to spend additional time reviewing Blockly levels 61 - 64 before using them in Python. This is a deceptively complex topic.

Terminology A subroutine is a general term for a block of code that is given a name and can be called from other parts of the program. Procedures and functions are specific types of subroutines but Python uses the word function as a general term.

Note that move_forward() is a subroutine in Rapid Router. The name is just a shortcut to a lot of code that moves the van one space forwards. You wouldn't want to type many lines of code every time you wanted to move the van.

Quiz (10 mins)

  • Slides 6 - 7: discuss the code. The code on the right is much easier to follow. Look at the main code in start. It tells you straight away that you do a wiggle (whatever that is…), go forwards and then wiggle again. If you want to know what wiggle is, you can look. Whereas, with the code on the left, you have to read all of it to figure out what is going on and there is repeated code.

  • Slides 8 - 11: Explore the ideas given in slides 6 - 7 with this example. How can you work out what to extract? Look for patterns. Sometimes you find a pattern that can go in a loop, sometimes it needs a subroutine. Additional loops would not help here because the code after the traffic light check changes each time. Discuss why it is important to give subroutines a descriptive name, e.g. lights instead of 'x'

Subroutines in Python (15 mins)

  • Slide 12: Levels 90 and 91 are used to practise the skills learned so far.

  • Slides 13 - 14: Defining and using subroutines. These slides focus on the syntax of a subroutine definition and call. Emphasise the brackets, colon and indentation.

Note the syntax for calling the subroutine. It needs the round brackets, just like with move_forwards()

  • Slides 15 - 16: Using main(). Look at the main code in b). It tells you straight away what you do. If you want to know what right_left() is, you can look. Whereas, with the code on the left, the helper code is at the top and you have to read down to find out what the program actually does.

  • Slides 17 - 18: Descriptive naming. It is important to use descriptive names for all variables and subroutines. They make your code much easier for you and others to read and for you to debug if you have errors.

  • Participants should do levels 101 and 102

Homework

  • For extra practice, participants can do levels up to 109, including any they did not finish during the lesson.

Last updated