Procedures

Cards (21)

  • A subroutine is a section of code that can be re-used several times in the same program
  • A subroutine is separate from the main code
  • A subroutine has to be called upon
  • Subroutines are designed to be repeated
  • What are the benefits of subroutines?
    They make programs easier to read - They reduce the duplication of code - In subroutines, complex problems are broken down into smaller chunks
  • There are 2 types of subroutines - procedures and functions
  • A procedure executes commands (e.g. printing something a certain number of times)
  • A function produces information by recieving data from the main program and returning a value to the main program
  • A function could take the radius of a sphere from the main program , calculate the sphere's area , and then return the value of the area to the main program
  • A function requires parameters to work
  • Parameters are the values that are to be transferred from the main program to the subroutine
  • A procedure is a type of subroutine that runs independently of the main program
  • A subroutine must be defined at the top of of the program before the main code , by typing def and the name of the subroutine
  • The main program starts beneath the subroutine , against the left side of the editor
  • In this code , the while true loop in the main program asks the user if they want to multiply , divide or stop the program - If they choose to multiply, the multiply subroutine is called , and this subroutine gets initiated and then returns to the main program once complete - If they choose to divide, the divide subroutine is called instead - Typing stop will break the loop
  • Subroutines must be written first , with the rest of the program underneath
  • Subroutines can be called in any order
  • Programming languages use local variables and global variables
  • A global variable can be used anywhere in the program
  • A local variable can only be used in the subroutine it is created in
  • This code uses global variables as it allows the program to ask the user to enter numbers in the main program