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 gedit
, VSCode
, Notepad++
, Atom
, Kate
.
The Python IDLE is fine too.
(b) You need a way to run your program.
Typing 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 python3 name-of-my-file.py
.
This 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.
Basic Arithmetic
- Can you find out how to raise a number to another number?
Functions
Here’s the page from the official documentation about how to define functions.
The Modulo Operator
- Can you define a function
isEven
that returnsTrue
orFalse
depending on whether the integer (passed an the only argument to this function) is even or not?
Generalising
- Now we can extend this function to
isDivisibleBy
by passing two integers:n
andd
. The function should returnTrue
ifn
is divisble byd
otherwise not.
Primality!
- 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.