How to think like a programmer -- Python Functions

Assumed audience: You are a TechLabs student pursuing the Data Science track. You require little hand-holding and prefer to refer to textbooks or denser materials if a concept doesn't make sense to you.

Context

I'm condensing chapters 2 through 4 into a single cheat sheet meant to orient you on how to think like programmer. Chapter 1 covered how to setup your development environment.

Functions

Your program consists of a series of functions.

Your task as a programmer is to create functions.

Functions take an argument and return a value.

It's basic math.

y = 8x + 10

This basic linear function returns y and takes x as an argument.

Python comes with a lot of built-in functions you should familiarise yourself with but we're especially interested in building our own.

You must use the def keyword to define a new function.

Use the return keyword to return the value (or another function).

If you get asked what the difference is between an argument and parameter then you could say that parameters are variables that serve as input for a function and arguments are the values we assign to those parameters.

Think of parameter as a placeholder.

And argument as an actual value.

It's fine to use them interchangeably, no-one will be confused.

Rewriting the linear equation:

# x is the parameter in this function
def y (x):
  return 8 * x + 10

You then call the function and pass it a value when you want to execute it.

# 8 is the value/argument
print(y(8))
# returns 74

Follow the flow of execution if you want to learn what a program does. This is a skill that takes time to develop.

Control the flow of execution

We learned about conditional execution in chapter 3 and about variables, expressions and statements in chapter 2.

A statement is just any line of code the Python interpreter can execute.

An expression is any combination of variables, values, and operators. The latter three should be familiar concepts from your math education.

You can't write a useful program without checking if certain conditions are met that would change the outcome and behaviour of the program.

We use if statements to control the flow of the program.

Sometimes we expect an error to occur, for instance, when the user provides input we can't accept.

Use the try and except keywords to handle this scenario. We catch the exception with a try statement. The except clause prints the error.

Here is a list of keywords you should keep handy:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

Guardian pattern

You should know how to protect your programs from producing errors. One way to do that is by implementing a guardian pattern.

x >= 2 and y != 0 and (x/y) > 2

This logical expression will stop at y != 0 if y equals zero. We want this to happen because y can't be zero in the expression (x/y).

Debugging

If you do get an error. Look at what kind of error it was because the Python interpreter will tell you and where it occurred.

Lambda functions aka anonymous functions

Define a variable and assign a lambda expression to it. It can only have one expression but any number of arguments.

# n is the parameter that will passed to the function
double = lambda n : n*2
# argument is 8
double(8)
# result
16

Practice tasks

I use Google Colab to work with the provided Jupyter notebooks.

Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and 1.5 for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your variable sum or use the sum() function. Print your computed pay.

def computepay(hrs, rate):
  hrs = float(hrs)
  rate = float(rate)
  if hrs > 40:
    overtime = hrs - 40
    overtimePay = overtime * rate * 1.5 
    return 40 * rate + overtimePay 
  else:
    return hrs * rate 

print(computepay(45, 10.5))

Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string.

# provided by author
 Score   Grade
>= 0.9     A
>= 0.8     B
>= 0.7     C
>= 0.6     D
 < 0.6     F

Solution

def computegrade(score):
  score = float(score)
  if score >= 0.9:
    return 'Grade A'
  elif score >= 0.8:
    return 'Grade B' 
  elif score >= 0.7:
    return 'Grade C'
  elif score >= 0.6:
    return 'Grade D'
  else:
    return 'Grade F'
print(computegrade(0.82)) 
print(computegrade(0.66)) 
print(computegrade(0.45)) 
print(computegrade(0.91)) 

curating the best of the web -

come explore!

media garden about ethos home