29. Subroutines

  • Subroutines (sometimes known as procedures) allow you to split your program into reusable chunks that you can call from any other part of your program
  • Subroutines always appear before the main program
  • They can work on their own or you can pass them values
  • Subroutines do not return values to the main program
#Subroutines first
def mySub():
    for i in range(0,3):
        print("hello")

def mySub2(word,times):
    for i in range(0,times):
        print(word)

#Main program starts below subroutines

#Call with no parameters
mySub()

#Call with parameters
mySub2('blah',5)

Tasks

  1. Type the code and make sure it works
  2. Create a subroutine that prints the cube of a number passed to it
  3. Save and label your code

Extension Task

You can create subroutines to do many things. Create subroutines to perform basic calculations (add, subtract, multiply, divide) that you can pass values to