Objectives

Students will be able to:

  • understand that a function is a module of code
  • understand that a function can be defined/implemented
  • understand that a function has to be called to be executed
  • understand that a function can have any number of parameters passed into it
  • understand that a function must return something, or it is not truly a function
  • translate program code to pseudocode and vice versa

Intro to Functions

modular coding

 

The Sleepy Scientist

A scientist is working in his office.

This is his routine:

  • He yawns 5 times
  • He slurps some coffee
  • If the coffee is too hot, he screams
  • He yawns 5 times
  • He enters some data into a computer program
  • He yawns 5 times

Task 1

Let's develop a modular solution to this problem.

Create a new file in your IDE (IDLE) called sleepyscientist

In your IDE, do what the video does.

Then continue to Task 2.

Task 2

While he is working, the scientist occasionally checks the room temperature.

Here is a useful function which will perform this task. It uses a random number generator!

def tempFunc():

temp = random.randint(15,45)

if temp > 35:

print(f"{temp} degrees: Stay inside!")

elif temp > 25:

print(f"{temp} degrees: drink water")

elif temp > 15:

print(f"{temp} degrees: take a walk")

else:

print(f"{temp} degrees: put on a jacket")

Type this function above the main() function definition and decide where/how you want to call it in the main program.

Continue to Task 3.

Task 3

After entering data, the computer program:

  • asks the doctor how much energy he still has
  • the doctor inputs a value between 1 and 10.
  • evaluates the response and gives some advice

Design a function, energyCheck(), to perform this task.

Call the function after the scientist enters data in the main program.

Kudos if you can incorporate exception handling and/or dealing with numbers entered outside the 1-10 range.

Continue to Adaptation.

Adaptation

Can you think of any other ways to make this program more fun or interesting?

You could design some more functions. And then call them when your program needs to use them!

Using your own ideas, create an adaptation of the Sleepy Scientist project.

Submission

Submit your .py file as instructed.

Tags

module function return identifier parameter pseudocode return typedefinecalldata type