Python Worksheet 1: Functions

24 Aug 2023, by Aadi

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

  1. 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

  1. Can you define a function isEven that returns True or False depending on whether the integer (passed an the only argument to this function) is even or not?

Generalising

  1. Now we can extend this function to isDivisibleBy by passing two integers: n and d. The function should return True if n is divisble by d otherwise not.

Primality!

  1. 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.

To sheet 2