Python Worksheet 1: Functions
24 Aug 2023, by
Back to all sheets
The zeroth step is to get your tools set up.
You need (a) a text editor, preferably one that can do syntax highlighting like
The Python IDLE is fine too.
(b) You need a way to run your program.
python3 in the Terminal should bring up the usual python interpreter.
Save files from the text editor in some directory, then
cd to that directory
and then run the files with
something.py file is called the source code, or even just the source.
It contains instructions that tell the computer what to do.
python3 is the computer programme that understands source code that is written in the language of Python version 3.
- Can you find out how to raise a number to another number?
Here’s the page from the official documentation about how to define functions.
The Modulo Operator
- Can you define a function
Falsedepending on whether the integer (passed an the only argument to this function) is even or not?
- Now we can extend this function to
isDivisibleByby passing two integers:
d. The function should return
nis divisble by
- Now that we have the ability to check divisibility, maybe we can check if a given number is prime or not. How would one go about doing this? Take a pen and paper and jot down what sequence of actions you take to decide whether a number is prime or not. Try it out with a couple of examples. Now turn your sequence of actions into a sequence of Python statements.