COS 100: Introduction to Programming
Interim 2022
Lab 7: Writing functions
In-class practice labs will not directly impact your grade
(although you'll get your standard participation point for staying on task),
and will serve to help you with homework projects.
Lab 7A: That's how functions function
-
Goal:
Get started with writing simple functions.
-
First read this entire lab (Tasks 1, 2, and 3, and the note below).
-
Task 1:
Write a function that takes an integer as input and returns a boolean:
-
If the input is even, return
True
.
-
Otherwise, return
False
.
-
Note: this function should NOT fetch any input from the user.
The input for this function will be supplied by the caller as an argument.
-
Before moving on, get this checked by the professor or TA.
-
Task 2:
Write another function that takes an integer as input and returns a boolean:
-
If the input is a prime number, return
True
.
-
Otherwise, return
False
.
-
Remember that we already have some code for determining whether a number is
prime or not. You can just adapt that code to fit this lab (package it up
as a function).
-
Task 3:
-
Prompt the user for an integer and report whether it is even or odd and whether it is prime.
-
You should call the two functions you've written above.
-
Make your reports to the user friendly; don't use jargons like "True" and "False."
-
Important note:
When you have a function that returns a boolean value, the convention is to name the function starting with
is
. In this case, is_even
and is_prime
would be appropriate names. Then when you read your if statement out loud, it should almost be in English, which is helpful for understanding your code.
Lab 7B: What's the function's function?
Challenge Lab 7C
-
Goal: Evolve your code.
-
Task:
Create a system to let the user interactively test properties about numbers.
Ask the user for a number, list some actions, and then repeatedly let the user choose actions until the user quits.
(See below for a sample run.)
-
Start with your code above.
Write a new function, perhaps creatively named
main2
.
Change the main()
call at the end of your code to main2()
in order to call this new main function.
-
You can (and should, for now) leave the old
main
function in the file.
This is another convenience of functions.
-
Sample run:
Available actions:
A. Determine if number is even.
B. Determine if number is prime.
C. Change the number.
D. List primes up to this number.
E. List this number of primes.
Q. Quit.
Integer, please: 23
Action? A
23 is odd.
Action? B
23 is prime.
Action? A
23 is odd.
Action? D
2 is a prime
3 is a prime
5 is a prime
7 is a prime
11 is a prime
13 is a prime
17 is a prime
19 is a prime
Action? C
Integer, please: 1
Action? A
1 is odd.
Action? B
1 is not prime.
Action? C
Integer, please: 2
Action? A
2 is even.
Action? B
2 is prime.
Action? X
Sorry, I don't understand.
Action? Q
Bye.
-
Challenge:
Most likely you have two lines that both prompt for integer from the user.
Try to make it so there's only one.