Modules and Functions, Lecture notes of Web Programming and Technologies

A module is simply a collection of functions and other Python statements that can be loaded using the import command, and then accessed.

Typology: Lecture notes

2022/2023

Uploaded on 03/01/2023

birkinshaw
birkinshaw 🇺🇸

4.7

(9)

239 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
ESCI 386 Scientific Programming,
Analysis and Visualization with
Python
Lesson 9 - Modules and Functions
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Modules and Functions and more Lecture notes Web Programming and Technologies in PDF only on Docsity!

ESCI 386 – Scientific Programming,

Analysis and Visualization with

Python

Lesson 9 - Modules and Functions

Defining and Using a Function

def sphere_area(r):

pi = 3.

return 4pir**

>>> sphere_area(5)

Lambda Operator

  • Python also has a simple way of defining a one-line function.
  • These are created using the Lambda operator.
  • The code must be a single, valid Python statement.
  • Looping, if-then constructs, and other control statements cannot be use in Lambdas.

bar = lambda x,y: x + y bar(2,3) 5 cube_volume = lambda l, w, h: lwh cube_volume(2, 4.5, 7)

Modules

 A module is simply a collection of functions and

other Python statements that can be loaded

using the import command, and then accessed.

 In addition to functions being defined within

modules, constants can also be defined.

 The functions and constants are accessed by

prefacing them with the name of the module.

Module Example

pi = 3.

def area(r): return 4.0pir**

def volume(r): return (4.0/3.0)pir**

import Sphere Sphere.pi

Sphere.area(5)

Sphere.volume(5)

Saved to ‘Sphere.py’

Namespace Consideration

  • We can import the module using a shorter

alias if we want.

import Sphere as s s.area(4)

Namespace Consideration (cont.)

  • We can use * to import all constants and

functions from a module without having to use

the module name.

from Sphere import * area(4)

  • However, this is not recommended!
  • You might inadvertently import two functions with the same

name from two different modules, which can cause confusion.

Documentation Strings

  • A document string is an optional string at the

beginning of a module or function that describes the module or function and its use.

  • The document string can be accessed via the

doc attribute.

  • It is a good idea to include at least a one-line document

string in your functions and modules.

  • The documents string should show usage and explain any

options.