Tigran, PHD Student

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Functions: Making programs modular

Lecture 7

Tigran, PhD student


Functions: Making programs modular
Key objectives when coding:
1. Make your code do what you want
2. Making it do that quickly

Both objectives can be fulfilled by breaking up your


code.

Programs should be broken up into parts that do specific


jobs,
especially if that job is done repeatedly.

This should be done as much as possible.


Functions: Making programs modular
Examples of such jobs:
•  finding the roots of a quadratic
•  testing if an integer is a prime number
•  finding the sum of a list of numbers etc.

Python (and most programming languages) provide a way of


doing this:
Functions

There are user defined functions and library functions.


We have already started using the math library for math.pi.

Let us look at some of the functions available in math.


Full list at: http://docs.python.org/3/library/math.html
For trigonometric functions,
angles are always in radians.

Another library that is essential when dealing with numbers is


NumPy (numpy)
For trigonometric functions,
angles are always in radians.
Differences:
instead of functions
degrees( ) and radians( )

Numpy uses
rad2deg( ) and deg2rad( )

Instead of
acos ->arccos

Full list: https://docs.scipy.org/doc/numpy-1.15.1/reference/ufuncs.html


User defined functions

Argument

Return value
User defined functions
A slightly more complicated function

Suppose
Wrong way round: define function first
A quick detour...
What are the %s doing in our strings?

An efficient way to print any value that your code produces is


by using % inside the string.

Outside of strings % is used for division


with a remainder

But when using % inside quotes another use is available...


A quick detour...
When we use %s, %f or %i in quotes and follow that by a %( )
right outside of quotes

we put the value inside %( ) into the print seamlessly.

Instead of:

These are String Formatting Operators


A quick detour...
Finally, the difference between %s, %i and %f is in their letters:

%s – String
The way you entered your value/string
– the way it will be printed

%i – Integer
No matter the number – it will be shown as an integer

%f – Float
No matter the number – it will be shown as a float (floating point)
User defined functions
Functions can take multiple arguments

You might also like