What is a procedure?

A procedure is a named group of programming instructions with a purpose and is called to perform a task based on the commands.

It is extremely important to name the procedure something that describes the purpose, method, or function because it makes it easier for others to read your code and for yourself when you revisit old code. Additionally, when there is an effefctively named procedure, it is much simpler to correct bugs and errors.

Which code is better?

Hack 1: Naming Procedures

Rename the procedure below with a name that better describes the purpose of the procedure.

The procedure is currently just called “procedure.” It compares the current grade with the existing quiz grade and replaces the original score if the current is higher.

def _comparing_grades(quiz_grade, current_points, total_points):
    # calculate current grade
    current_grade = (current_points / total_points) * 100

    if current_grade > quiz_grade:
        quiz_grade = current_grade

    return quiz_grade

quiz_grade = 85  # Initial quiz grade
current_points = 90  # Current points earned
total_points = 100  # Total points for the quiz

new_quiz_grade = _comparing_grades(quiz_grade, current_points, total_points)

print(f"Old quiz grade: {quiz_grade}")
print(f"New quiz grade: {new_quiz_grade}")

Old quiz grade: 85
New quiz grade: 90.0

Function Parameters

A function can have one or more parameters that can be passed into the function as local variables to use in the procedural function. The variables that can be passed in the function are called parameters. The data passed in when the function is called are called arguments.

Parameters: input values of a procedure

Arguments: specify the parameter values when a procedure is called

def triangle_area(length, width): # parameters passed in two variables: length and width, returns area
    area = 1/2 * length * width # calculates area from the length and width
    print("length:", length)
    print("width:", width)
    return area # returns area

# examples
print(triangle_area(3, 4)) # the arguments here are 3 and 4, which becomes the parameters length and width respectively
print(triangle_area(6, 8))
print(triangle_area(12, 89))
length: 3
width: 4
6.0
length: 6
width: 8
24.0
length: 12
width: 89
534.0

Procedure Algorithm / How Procedures Work

Remember that procedures are essentially a set of programming instructions, or lines of code, that accomplish a goal. When executed, each line of code is executed in order (step after step after step) to get to the goal.

Regular code/Python

# Procedure called "applyTax" that applies a percent tax to a price
def applyTax(price, percentTax): # When writing a procedure, first decide what parameters you will need to accomplish your goal
    # Step 1: Calculate the amount taxed
    taxAmount = price * percentTax/100

    # Step 2: Add the amount taxed to the price to get the end amount
    endAmount = price + taxAmount

    return endAmount

# Use procedure to apply a 50% tax to a price of $10
cost = applyTax(10, 50)
print(cost)
15.0

CollegeBoard Pseudo-Code

  • Note that the pseudo-code below has the exact same purpose as the actual code above. Ignore the breaks and spaces since they are used for formatting.

    Differences between prseudo-code and Python:

  • Pseudo-code uses “PROCEDURE” instead of “def”
  • Pseudo-code uses “<–” instead of “=”
  • Pseudo-code uses “{}” instead of “:” to mark where a procedure starts and ends

Pseudo-code example

PROCEDURE applyTax (price, percentTax)
{
    taxAmount <– price * percentTax/100
    endAmount <– price + taxAmount
    return endAmount
}

Hack 2: Robot Pseudo-Code

Instructions:

  • The blue triangle represents a robot that moves in a grid of squares. The tip of the triangle indicates where the robot is facing.
  • Write a procedure that allows the robot to make a detour around a block by moving to the left.

Commands

  • MOVE_FORWARD() - Moves the robot forward one square
  • MOVE_BACKWARD() - Moves the robot backward one square
  • ROTATE_LEFT() - Rotates the robot 90 degrees left
  • ROTATE_RIGHT() - Rotates the robot 90 degrees right

procedurerobot ROTATE_LEFT() MOVE_FORWARD() ROTATE_RIGHT() MOVE_FORWARD() MOVE_FORWARD() ROTATE_LEFT() MOVE_FORWARD() MOVE_FORWARD()

Procedure Return Values

When a procedure is run, it executes a series of calculations or commands and at some point and needs to provide a useful result. The return statement is what allows us to return a useful value back to the calling code. The returns statement can return various types of values such as booleans, integers, strings, etc.

Procedure Calls

Calling: This involves specifying the function name followed by parentheses, and passing any required arguments inside the parentheses.

When a function is called, the program control jumps to the function definition, and the statements inside the function are executed. After the function completes its task, the control returns to the point where the function was called.

Hack 3: Create and Call a Procedure

Define a function named calculate_grade that takes a student’s score as a parameter and returns ‘Pass’ if the score is 50 or more, and ‘Fail’ otherwise.

# your code here
def grade_calculater(score):
    if int(score) >= 50:
        print ("You passed")
    else:
        print ("you failed")
    
score = input("What's your score")
grade = grade_calculater(int(score)) 


You passed

Homework

Instructions

There are two total problems:

  1. An easy regular code (Python) problem
  2. A medium pseudo-code problem
  3. A hard regular code (Python) problem

Completing question 1 and 2 gets you 0.9/1 if you do it correctly. Completing/attempting question 3, adding creativity, and adding good comments will potentially raise you above 0.9.

### Question 1
### Write a procedure to apply a percent discount to a set price. See the example about applying tax if you're stuck.

def apply_discount(original_price, discount_percent): #the procedure here deifnes two things to be applied, one the original price and the amount of discount on the orginal price i.e. the discount percent
    discount_decimal = discount_percent / 100 # this command here divides the discount percent by 100 to give an decimal
    discount_amount = original_price * discount_decimal # The decimal derevied from the preivous line of code is mulitplied by the orinal price
    discounted_price = original_price - discount_amount # the produce is set as discounted_price
    return discounted_price 

original_price = 250.0 # if the original price is $200 
discount_percent = 23.0  # and the discount percent is 25 percent
discounted_price = apply_discount(original_price, discount_percent) # then a funciton is defined as apply_discount which extracts code from above to calculate the overall price after the discount.
print("Discounted Price:", discounted_price) # the value is then printed out.


Discounted Price: 192.5
# your code here

Question 2

Create your own robot problem! Include a picture with a square grid to represent the map and triangle to represent the robot. Add a flag to a square to represent the end-point and a shaded-in block to represent a detour. Write a procedure in pseudo-code to move the robot from the start, past the detour, and to the end point.

Add your image here by adding the link between the “” and removing the comment formatting:

# your code here
Procedure move_robot(start, turn, end)

ROTATE_RIGHT()
MOVE_FORWARD()
MOVE_FORWARD()
MOVE_FORWARD()
ROTATE_LEFT()
ROTATE_LEFT()
MOVE_FORWARD()
ROTATE_RIGHT()
MOVE_FORWARD()
ROTATE_LEFT()
MOVE_FORWARD()
ROTATE_LEFT()
MOVE_FORWARD()
ROTATE_RIGHT()
MOVE_FORWARD()
ROTATE_RIGHT

// sorry couldnt figure out how i can create an add the robot image
// my code is something of a loop 
// the robot, starts at the edge of the square, link the overall area
// turns right and moves 3 squares forward
// turns left twice and thus faces the opposite direction
// move a step and encountures are new object in front of it
// takes a detour around the object
// Moves back into its original sqaure
// turns right to come back to the original position
  Cell In[19], line 3
    Procedure move_robot(start, turn, end)
              ^
SyntaxError: invalid syntax

Question 3

Create a program that asks for user input of an integer n, and return an array that contains all the prime numbers up to the number n (inclusive). Remember to use multiple different functions to better organize the code and increase efficiency.

def is_prime(num): # the code is defined by the is_prime function which runs throughout the entiretly of the code
    if num <= 1: # the user is asked an input from which the number is tested using a variety of test cases, number one being whether it's less than or equal to 1, it it is then the number would return false or invalid because in definitation primes are grater than 1
        return False
    if num <= 3: # test 2, defines whether or not the number is less than or equal to 3, if then the number is returned true or is a prime
        return True
    if num % 2 == 0 or num % 3 == 0: # the third test is where the number divided by 2 or 3 returns an answer of 0, if then the number is not prime as one divisble by 2 or 3 would also be divisible by a couple of other numbers as well
        return False
    i = 5 # testing a the numebr with 5
    while i * i <= num: 
        if num % i == 0 or num % (i + 2) == 0: # since this a test for the number 5, then if the numebr is either divisible by 5 ot is the number is divisible by the sum of 5 and 2 which equals 0 then the number is not prime; thus a false statment
            return False
        i += 6
    return True
def generate_primes_up_to_n(n): # address the code to generate al the prime number up until n or the number input from the user
    primes = []
    for i in range(2, n + 1): # a range is set for the number, from 2 till the number plus one, this helps to even out the code and helps the computer decide from which to which number does it need to output primes from
        if is_prime(i):
            primes.append(i)
    return primes
def main(): # now that all the major testing code are done above, the main part of the code would be to take in an input from the user and test for primes.
    # all the above are tests to deicide if the number input from the user is a prime or not, these test help the code to first decide is the number is prime or not, returing a true or false statement, and then come to the next part of the code
    # the next part of the code where the range between the numbers are set and the primes between the two are decided
    try:
        n = int(input("Enter an integer n: ")) # input from the user is taken into consideration
        if n < 2: # test case irl: testing is the numebr is less than 2
            print("There are no prime numbers for n < 2.")
        else:
            prime_numbers = generate_primes_up_to_n(n) # else if the number pases all the test cases above, then the range of two number is set and the primes between teh two number are calucalted using the code that was predefined above
            print("Prime numbers up to", n, "are:", prime_numbers)
    except ValueError:
        print("Invalid input. Please enter a valid integer.") # for an invalid input from the user, a fraction or decimal are all counted as invalid inputs
if __name__ == "__main__":
    main()



# tests
print(is_prime(5)) # test case one: 5; prime
print(is_prime(12)) # test case two: 12; not prime
print(is_prime(35)) # test case three: 35; not prime
Prime numbers up to 600 are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599]
True
False
False