Chapter 6

Using functions

CS1302 Introduction to Computer Programming

6.1 Introduction to Using Functions

6.2 Functions and Modules

Import keyword: from math import sqrt

Three important parts: Name, Parameters, Result type

6.3 The Built-in Functions

Automatically available to any Python program:

no import statement is required.

6.4 Standard Mathematical Functions

6.4 Standard Mathematical Functions

The standard math module provides much of the functionality of a scientifific calculator.

>>> import math

>>> dir(math)

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'g amma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

>>>

6.5 time Functions

Warning

time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead

6.5 time Functions

6.6 Random Numbers

All algorithmic random number generators actually produce pseudorandom numbers, not true random
numbers.

6.7 System-specifific Functions

The sys.exit function accepts a single integer argument, which it passed back to the operating system
when the program completes. The value zero indicates that the program completed successfully; a nonzero
value represents the program terminating due to an error of some kind.

6.8 The eval and exec Functions

eval: evaluate a string in the same way that the interactive shell would evaluate it.

6.9 Turtle Graphics

Example:

Use functions from Python’s Turtle graphics module to draw a sunflower

6.9 Turtle Graphics

6.10 Other Techniques for Importing Functions and Modules

import *: import all

CS1302 Chapter 6

By Sally ZENG

CS1302 Chapter 6

Lecture 4 part 1

  • 151