Calling Procedures

Slide 1:

  • A procedure is a named group of programming instructions that may have parameters and return values.
  • Procedures are referred to by different names, such as method or function, depending on the programing language.
  • Parameters are input values of a procedure. Arugments specify the values of the parameters when procedure is called.
  • A procedure call interrupts the sequential execution of statements causing the program to execute the statements within the procedure before continuing. One the last statement in the procedure (or a return statement) has executed, flow or control is returned to the point immediately following where the procedure was called.

Slide 2:

  • When calling procedures, it's important to take notice to whether it returns data, or a block of statements.
  • If the procedure just returns a block of statements, you call the procedure by referring to the procedure name, and inputting the arguments.
  • If the procedure returns some sort of data like a boolean or value, then you will assign that value to a variable

Slide 3:

  • Assume the Temperature outside is Fahrenheit.
  • The procedure convertFahrenheit is intended to convert from Fahrenheit to Celsius.
  • Convert the following psuedocode to python
def convertFahrenheit(temperature):
    celsius = temperature - 32
    celsius = celsius * 5/9
    return celsius

outsideTemp = input("Enter temperature in celsius")
outsideTemp = int(outsideTemp)
convertFahrenheit(outsideTemp)
0.5555555555555556

Developing Procedures

Slide 8:

Picking a decriptive name is important in case you revisit the code later on (separate words with capitals) There are 2 different types of procedures- ones that return a value and those that simply execute a block of statements Steps of developing procedure: picking a useful name, thinking of parameters (what data does the procedure need to know), making a flowchart or writing procedure in pseudocode, and actually developing the procedure.

Slide 9:

In this example, a teacher is writing a program that will replace the grade on a previous quiz if the new grade is better than the previous.

  • What would be a good name for this procedure?
  • What parameters do we need for this procedure?
  • Try writing this procedure out in python based on the given pseudocode

procedure goes here

currentGrade <- currentPoints / 40 currentGrade <- current Grade * 100 if currentGrade > quizGrade quizGrade <- currentGrade

def quiz_grader():
    currentPoints = int(input("Amount of points scored:"))
    totalPoints = int((input("Amount of  points possble")))
    grade = currentPoints/totalPoints * 100
    print(str(grade)+"% was the score this student recieved on this quiz they scored " + str(currentPoints) + " out of " + str(totalPoints) + " points.") 
quiz_grader()
5.0% was the score this student recieved on this quiz they scored 2 out of 40 points.

Procedural Abstraction

  • One type of abstraction is procedural abstraction which provides a name for a process and allows a procedure to be used only knowing what it does and not how it does it
  • This is very helpful in managing complexity in a program
  • Subdivision of a program into separate subprograms is called modularity
  • A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for program reuse, which helps manage complexity
  • When a pre-written procedure is called, you don’t necessarily need to know the details of this, just what it does and how to call it
  • Simply, procedural abstraction is naming and calling a prewritten procedure
  • Making sure to include the right arguments so the procedure can do what its supposed to do is crucial

Complexity Example

One of the biggest advantages of procedural abstraction is managing complexity.

Think about the process of simplifying the code? What do you think the advantage of the code segment on the left is?

Code Segment 1 Code Segment 2
ROTATE_LEFT() detourLeft()

MOVE_FORWARD()|turnCorner()| ROTATE_RIGHT |MOVE_FORWARD()| MOVE_FORWARD()|MOVE_FORWARD()| MOVE_FORWARD() ROTATE_RIGHT() MOVE_FORWARD() ROTATE_LEFT() MOVE_FORWARD() ROTATE_LEFT() MOVE_FORWARD() MOVE_FORWARD MOVE_FORWARD()

Hacks

  • Write a python procedure about something which can help you in school, for example the teacher’s function we spoke about earlier.
  • Points will be awarded based on creativity and functionality
  • 0.1 points will be deducted for late submissions
  • Submit the notes with all blanks filled in (scored out of 0.5 points) and the python procedure (scored out of 0.5 points) by Monday 12/12 at 11:59 PM.
import time

def AssignmentTimer(x):
    print("You have " + str(x) + " minute/s to work on this assignment.")
    try:
        time.sleep(x*60)
    except KeyboardInterrupt:
        # allows the user to cancel the timer
        print("Timer cancelled.")
    else:
        print("Time is up! Take a break!")

while True:
    minutes = int(input("Enter the number of minutes you would like to work on your assignment: "))
    AssignmentTimer(minutes)

    # Allows typos in the user's response if they want another timer
    while True:
        response = input("Do you want to start another timer? (yes/no)")
        if response.lower().strip() == "no":
            print("Goodbye!")
            break
        elif response.lower().strip() == "yes":
            break
        else:
            print("Invalid response. Please enter 'yes' or 'no'.")

    # Stops the loop if the user doesn't want another timer
    if response.lower().strip() == "no":
        break

    # Demonstration of an algorithm that has a use case that could be useful for school in a way
    # that allows the user to input the number of minutes they want to work on their assignment
    # and then the program will start a timer for that amount of time and then the user can
    # cancel the timer if they want to stop working on their assignment or the timer will
    # automatically end after the amount of time the user inputted and if they don't want another timer.
    # Allows the user to manage thier time better and be more productive throug taking regular breaks
    # and manage the amount of time certain assignments take to complete.
You have 1 minute/s to work on this assignment.
Time is up! Take a break!
Invalid response. Please enter 'yes' or 'no'.
You have 2 minute/s to work on this assignment.
Time is up! Take a break!
You have 69420 minute/s to work on this assignment.
Timer cancelled.
Goodbye!