11
8/24/18 1 Lecture 10 Functions, Arguments, and Modules What are we going to cover today? Function Calls Arguments Return Values Tuples Modules in Python Functions – Main Ideas Functions are basically a section of code that gets specified separately from the rest of the code. Code Section 2 Code Section 1 Code Section 3 Code Section 4 Code Section 5 Code Section 6 Main Program (Code) Functions – Main Ideas Functions are basically a section of code that gets specified separately from the rest of the code. Function A Code Section 2 Code Section 1 Code Section 3 Function B Code Section 4 Code Section 5 Code Section 6 Main Program (Code) Functions Functions – Main Ideas Functions are basically a section of code that gets specified separately from the rest of the code. When following code, we will encounter a function call Also called “invoking” the function Causes the code in the function to be executed next Function A Code Section 2 Code Section 1 Code Section 3 Function B Code Section 4 Code Section 5 Code Section 6 Main Program (Code) Functions Function Call Function Call Functions – Main Ideas Functions are basically a section of code that gets specified separately from the rest of the code. When following code, we will encounter a function call When a function is finished, we return to the place it was called from Function A Code Section 2 Code Section 1 Code Section 3 Function B Code Section 4 Code Section 5 Code Section 6 Main Program (Code) Functions Function Call Function Call Return Return

Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

1

Lecture 10Functions, Arguments, and Modules

What are we going to cover today?

• Function Calls

• Arguments

• Return Values

• Tuples

• Modules in Python

Functions – Main Ideas

• Functions are basically a section of code that gets specified separately from the rest of the code.

Code Section 2

Code Section 1

Code Section 3

Code Section 4

Code Section 5

Code Section 6

Main Program (Code) Functions – Main Ideas

• Functions are basically a section of code that gets specified separately from the rest of the code.

Function ACode Section 2

Code Section 1

Code Section 3

Function BCode Section 4

Code Section 5

Code Section 6

Main Program (Code) Functions

Functions – Main Ideas

• Functions are basically a section of code that gets specified separately from the rest of the code.• When following code, we will

encounter a function call• Also called “invoking” the

function• Causes the code in the function

to be executed next

Function ACode Section 2

Code Section 1

Code Section 3

Function BCode Section 4

Code Section 5

Code Section 6

Main Program (Code) Functions

Function Call

Function Call

Functions – Main Ideas

• Functions are basically a section of code that gets specified separately from the rest of the code.• When following code, we will

encounter a function call• When a function is finished, we

return to the place it was called from

Function ACode Section 2

Code Section 1

Code Section 3

Function BCode Section 4

Code Section 5

Code Section 6

Main Program (Code) Functions

Function Call

Function Call

Return

Return

Page 2: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

2

Functions – Main Ideas

• Functions are basically a section of code that gets specified separately from the rest of the code.• This presents (along with

sequential, conditional, and repetition) another model for organizing computation

Function ACode Section 2

Code Section 1

Code Section 3

Function BCode Section 4

Code Section 5

Code Section 6

Main Program (Code) Functions

Function Call

Function Call

Return

Return

Why do we have functions?

• Prevent re-writing the same code repeatedly• We can call the same function several times

• Helps conceptually separate parts of the code• A sections of code that can be thought of as a single action can be separated.• We don’t see a big block of code that’s separated from other things

• Can write a function separately from the rest of the code

• Today, we’ll be focused on the last reason – we’ll return to the others in future weeks.

Function calls

• We’ve actually been seeing many function calls already!• Function calls have the form:

<function name>(<arguments>)

Function calls

• We’ve actually been seeing many function calls already!• Function calls have the form:

<function name>(<arguments>)

First we have the name of the function

Function calls

• We’ve actually been seeing many function calls already!• Function calls have the form:

<function name>(<arguments>)

Then, there are parentheses.All function calls have parentheses after the function name.

Function calls

• We’ve actually been seeing many function calls already!• Function calls have the form:

<function name>(<arguments>)

Inside the parentheses is, possibly, a list of arguments.Some function calls do not have any arguments.

Arguments are sometimes called “parameters”.

Page 3: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

3

Function calls

• We’ve actually been seeing many function calls already!• Function calls have the form:

<function name>(<arguments>)• Some examples we’ve seen:• print()• input()• int(), float(), str()• open()• len()• sqrt()• etc.

Passing Data To/From Functions

• Since functions are defined separately from the rest of the code, they don’t necessarily have access to the same data as in the main code• We pass data into the function using arguments• For example, print("Howdy!") is passing the string “Howdy” to the

function• Ideally, all the data the function needs should be passed in through the

arguments.• Data is returned from the function by a return value• For example, input() will return a string – the string entered in the

console.• We can then assign the returned value to some variable, or use it in an

expression

Functions as a “black box”

• It is often helpful to think of functions as a “black box”• They take input (via arguments/parameters)• They do something (but you don’t need to understand exactly how)• They return some value

FunctionArguments

Return Value

Passing in Data

• Often, functions will need more than one piece of data• This is usually specified by giving several arguments, separated by

commas• e.g. print(x,y)

• Some functions will take varying numbers of arguments, or even no parameters• e.g. input(), input("Enter something:")

Returning Data

• In most functions, the data returned is either nothing, or just a single value• Example: sqrt(x) returns the square root of x• Sometimes, we want to return more than one value.• For this, we need to understand tuples

Tuples

• A tuple is like a list, with one important distinction: it cannot change values• The term used is that it’s immutable• We can still use it to compute with

• Where lists use brackets [], tuples use either parentheses or just comma separated lists:

my_tuple = (1, 2, 3)my_tuple = 1, 2, 3my_list = [1, 2, 3]

Page 4: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

4

Tuple operations

• We can define tuples:my_tuple_A = (1, 2, 3)my_tuple_B = 1, 2, 3my_list = [1, 2, 3]print(my_tuple_A)print(my_tuple_B)print(my_list)

Output(1, 2, 3)(1, 2, 3)[1, 2, 3]

Tuple operations

• Most operations are just like those for lists:my_tuple = (1, 2, 3, 4)

print(my_tuple[2])print(my_tuple[1:3])print(len(my_tuple))

Output3(2, 3)4

Tuple operations

• We can assign values from a tuple:my_tuple = (1, 2, 3)

a, b, c = my_tupleprint(a)print(b)print(c)

Output123

Tuple operations

• But, assignment is not allowed:my_tuple = (1, 2, 3, 4)

my_tuple[2] = 5

OutputTypeError: 'tuple' object does not support item assignment

Returning tuples

• A function can only return one value• But, that value can be a tuple• Then, you can assign the parts of a tuple to various values

• Example:a, b = some_function()

Returning tuples

• A function can only return one value• But, that value can be a tuple• Then, you can assign the parts of a tuple to various values

• Example:a, b = some_function()

The function will return a tuple

Page 5: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

5

Returning tuples

• A function can only return one value• But, that value can be a tuple• Then, you can assign the parts of a tuple to various values

• Example:a, b = some_function()

Then, those tuple values are assigned to the two variables, a and b

Returning tuples

• A function can only return one value• But, that value can be a tuple• Then, you can assign the parts of a tuple to various values

• Example:a, b = some_function()

• This is usually the way that functions will return “multiple” values.

Where do we get functions?

• Built-in functions• Default functions included in Python• Example: print(), input()

Some Useful Functions

• There are some built-in functions that are particularly useful for lists:• len(A) – for the list/tuple A, gives the size (we already saw this)• max(A) – for the list/tuple A, gives the maximum element• min(A) – likewise for the minimum element• sum(A) – the sum of all the elements in a list/tuple A

Some Useful Functions

• There are other operations defined for lists that are built in.• These have the form A.<function>() NOT <function>(A). This

is due to the way these list functions are defined – as “belonging” to the list, A, rather than as a standalone function.• A.append(B) – appends B to list A (we saw this already)• A.insert(B,C) – inserts C into list A at point B• A.sort() – sorts the list from smallest to largest• A.index(B) – gives the index where B first occurs in list A• A.pop(B) – removes the element at index B from the list, and returns it

Where do we get functions?

• Built-in functions• Default functions included in Python• Example: print(), input()

Page 6: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

6

Where do we get functions?

• Built-in functions• Default functions included in Python• Example: print(), input()

• Functions a user writes• We’ll talk about this next week

Where do we get functions?

• Built-in functions• Default functions included in Python• Example: print(), input()

• Functions a user writes• We’ll talk about this next week

• Functions we import from modules• We’ll talk about this next!

An Analogy

• Imagine that you were going to keep track of information – and you can read and write• But, imagine that the only things you could have on paper were

things you wrote yourself…• You could, over time put together a lot of documents containing information

you once knew• But, think of how limited the range of knowledge you could store is!

An Analogy

• Instead, imagine having access to a large library of information that other people had put together• You would have far more information

available• You would have to write down less of your

own knowledge

• This is the motivation behind libraries in programming

Modules and Packages

• In Python, we refer to one of these collections as a module• This can be thought of as a single file, containing Python code that someone

else wrote

• Sometimes, multiple related modules are put together into a package• We can import the module/package into our own code• Giving us access to everything that was written there!

• Note: the more generic term used in programming for this type of organization (a separate file/structure that gets brought in to another program) is “library”.

Importing Modules

• Typically, the main thing a module does is to define functions• Sometimes some other things are also defined, like some variables

• We’ve already seen an instance of this – using the math module• Defined functions for sin, sqrt, etc.• Also defined some constants, like pi

• To have access to everything in a module, we have to import the module• There are a few ways of doing this

Page 7: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

7

Importing a whole module

• To import a whole module, just use the command:import <module name>

• This will make all the functions in that module available for use in your program.

Importing a whole module

• To import a whole module, just use the command:import <module name>

• This will make all the functions in that module available for use in your program.• To use those functions, you must call the function starting with the

module name:<module name>.<function name>(<arguments>)

Importing a whole module

• To import a whole module, just use the command:import <module name>

• This will make all the functions in that module available for use in your program.• To use those functions, you must call the function starting with the

module name:<module name>.<function name>(<arguments>)

The module name is the name of the module.It should have been imported earlier

Importing a whole module

• To import a whole module, just use the command:import <module name>

• This will make all the functions in that module available for use in your program.• To use those functions, you must call the function starting with the

module name:<module name>.<function name>(<arguments>)

A period is placed between the module name and the function name.It shows the function will be the one coming from that module.

Importing a whole module

• To import a whole module, just use the command:import <module name>

• This will make all the functions in that module available for use in your program.• To use those functions, you must call the function starting with the

module name:<module name>.<function name>(<arguments>)

Next is the name of the function itself.

Importing a whole module

• To import a whole module, just use the command:import <module name>

• This will make all the functions in that module available for use in your program.• To use those functions, you must call the function starting with the

module name:<module name>.<function name>(<arguments>)

Finally there are the parentheses, possibly containing arguments.

Page 8: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

8

Example

• The math module has a function, sqrt, that can be used to compute the square root.• We could call that routine as follows:

import matha = math.sqrt(2.0)

Importing individual functions

• We can also import individual functions from a module• The command to do this is:

from <module name> import <function names>

Importing individual functions

• We can also import individual functions from a module• The command to do this is:

from <module name> import <function names>

Start with the command “from”

Importing individual functions

• We can also import individual functions from a module• The command to do this is:

from <module name> import <function names>

The module name is the name of the module

Importing individual functions

• We can also import individual functions from a module• The command to do this is:

from <module name> import <function names>

Then there is the command “import”

Importing individual functions

• We can also import individual functions from a module• The command to do this is:

from <module name> import <function names>

Finally is the list of functions to import from the module, separated by commas.

Page 9: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

9

Importing individual functions

• We can also import individual functions from a module• The command to do this is:

from <module name> import <function names>• To use the functions imported this way, you don’t need to list the

module name first.

Importing individual functions

• We can also import individual functions from a module• The command to do this is:

from <module name> import <function names>• To use the functions imported this way, you don’t need to list the

module name first.• Example:• To import and use the sqrt and sin functions from the math module:

from math import sin, sqrta = sqrt(2.0)b = sin(3.14159/4)

Importing all functions

• We can import all the functions from a module by using an * in the place of the list of functions.• We’ve been doing this with the “from math import *” command

• This is generally frowned upon• You probably don’t know everything you’re bringing in• You could bring in a new function that conflicts/overrides an existing function

that you want to keep• The new name supersedes the old.

Packages

• Packages are basically a collection of related modules• A package will be made up of individual modules• To access a module in a package, you use the format:

<package name>.<module name>• For example:

matplotlib.pyplot• This refers to the module pyplot in the package matplotlib

• These are often called “submodules”

Renaming

• Sometimes you want to rename a function for your own use• To save typing, or give a more consistent name with things you are using.

• You can do this by adding “as” on to the end of the from…import command• Example:

from math import sqrt as sra = sr(2.0)

• This code defines sqrt to be referred to as sr. Then, sr is used for the function calls.

Getting Modules

• There are several sources for modules• There are default modules included with each Python install• The Python Library Reference• Many commonly used modules, such as:

• math (math operations),• cmath (math for complex numbers)• random (random numbers)• etc. (more than 200 more)

• You still have to import them to use them.• See https://docs.python.org/3/library/index.html

Page 10: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

10

Getting Modules

• There are several sources for modules• There are default modules included with each Python install• You can install them from external sources• We will go into this in a moment• Some are automatically installed when you install certain “versions” of Python

• Anaconda python automatically includes several additional modules, useful for math/science/engineering computations

Getting Modules

• There are several sources for modules• There are default modules included with each Python install• You can install them from external sources• You can write your own!• This is basically just writing and saving a python file• But, there are some details about how to set it up so that it’s more useful

Installing additional modules

• To get additional modules, you need to first install them on your computer.• A list of all registered packages/modules available is at the Python Package

Index• https://pypi.python.org/pypi• These are not necessarily very good packages! They are just packages that

people enter into the repository• Many new packages are entered daily

• You can install them using the pip routine or the conda package manager

Running pip

• Pip is a routine for installing Python packages• With it, installing a new package is very simple

• You do need to be sure pip is installed and up to date• it should be as part of installing Python, but might need to be updated

• Once installed, you should be able to run pip from the command line of your system• cmd for Windows• Terminal for Mac OSX

• Just enter pip install <package name>• See documentation: https://pip.pypa.io/en/stable/

Running conda

• Conda is a package manager for use with the Anaconda distribution of Python• It includes both graphical and command-line interfaces to help see

which packages are installed, and to install more• See documentation: https://conda.io/docs/user-guide/

Getting and Using Modules

• As you program in Python, you will probably find there are modules you’d like to use (we’ll see two of these in lab).• Usually, modules have some documentation with them, explaining

how they work.• Most modules have an entire “philosophy” about how the various

components they provide should work and be used together.• When using modules, it is more to read and understand how a

module works than it is to get it installed on your system.

Page 11: Lecture 10 - CEProfs · Lecture 10 Functions, Arguments, and Modules What are we going to cover today? •Function Calls •Arguments •Return Values •Tuples •Modules in Python

8/24/18

11

Lab/Homework today

• You’ll practice making function calls• Using plotting commands and creating new data storage types

• The idea is for you to learn to use (parts of) 2 packages:• numpy – a package for performing vector and matrix operations• matplotlib – a package for creating data plots• These are two of the most widely used Python packages in engineering.