Understanding Functions in Programming
Understanding Functions in Programming
Using Functions
CS1302 Introduction to Computer Programming
Content
1. How to import package/module/function
2. How to define and use function
Motivation
How to reuse code so we can write less?
When we write a loop, the code is executed multiple times, once for each iteration.
{important}
Functions
$y=f(x)$ is a function in math. What is function in coding?
Function is a block of code that performs a specific task.
You can pass data, known as arguments or parameters , into a function.
A function can return data as an output.
when you use a function, it's known as we call a function or function
call
In [4]: print(print("cs1302"))
cs1302
None
In [6]: input()
Out[6]: 'test'
def calculate_area(radius):
area=[Link]*radius**2
return area
21.237166338267002
3.14
--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
Cell In[10], line 11
9 print(calculate_area(2.6)) #this is function call
10 print(PI) #this is correct because PI is a global variable
---> 11 print(area) #this is wrong cause area is defined in calculate_are
a, and cannot be accessed outside the function
8.0
In [13]: input("Please input an integer value: ") # calling the input() function
Out[13]: '10'
[Link] 3/34
2/17/25, 3:56 PM Using Functions
{note}
- the argument can also be a function call like function
composition in mathematics.
- In math we can use y=f(g(x)). Likewise, we can call a
function as function1(function2(x))
- In this example, the return data of *input()* is used
as the parameter of *print()*
- Before a function call is executed, its arguments are
evaluated first from left to right.
- when we call a function such as f(a,b,c,d), the
evaluation order is a->b->c->d; therefore, user's first
input will be printed after `1st input`, and user's second
input will be printed after `2nd input`
[Link] 4/34
2/17/25, 3:56 PM Using Functions
Number of digits of x: 4
In [12]: log10(100)
Out[12]: 2.0
The above example imports both the functions log10 and floor from math to
compute the number $\lfloor \log_{10}(x)\rfloor$ of digits of a strictly positive integer
$x$.
log(x,y) : base is y
log2(x) : base is 2
log10(x) : base is 10
floor(x): returns floor of x, i.e., the largest integer not greater than x.
floor(1.2) returns 1, floor(5.4) returns 5
ceil(x): returns ceiling value of x, i.e., the smallest integer not less than x
ceil(1.2) returns 2, ceiling(5.4) returns 6
How to import all functions from a library?
syntax:
from module_name import *
The above uses the wildcard * to import (nearly) all the functions/variables
provided in math , except names starting with an underscore.
In [16]: from math import * # import all except names starting with an underscore
print('{:.2f}, {:.2f}, {:.2f}'.format(sin(pi/6),cos(pi/3),tan(pi/4)))
Out[18]: The main difference between the built-in function `pow()` and `[Link]
()` in Python is that `pow()` can handle three arguments (base, exponen
t, and optional modulus) and is generally faster, whereas `[Link]()` t
akes only two arguments (base and exponent) and returns a floating-point
result. This means `pow()` is more versatile and efficient, especially w
hen dealing with large integers or modular arithmetic, making it the pre
ferred choice for most use cases, while `[Link]()` is usually used whe
n working with floating-point numbers or when the math module is already
being used for other calculations.
In [19]: print(__builtin__.pow(-1,1/2))
print('{:.2f}'.format(__builtin__.pow(-1,1/2)))
import math
print([Link](-1,1/2))
(6.123233995736766e-17+1j)
0.00+1.00j
--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
Cell In[19], line 4
2 print('{:.2f}'.format(__builtin__.pow(-1,1/2)))
3 import math
----> 4 print([Link](-1,1/2))
The function pow imported from math overwrites the built-in function pow .
Unlike the built-in function, pow from math returns only floats but not integers
nor complex numbers.
We say that the import statement polluted the namespace of the global frame
and caused a name collision.
How to avoid name collisions?
We can use the full name (fully-qualified name) [Link] prefixed with the module
name (and possibly package names containing the module).
[Link] 6/34
2/17/25, 3:56 PM Using Functions
[Link] 7/34
2/17/25, 3:56 PM Using Functions
#method 2
from package_name import module_name as short_name
print(__builtin__.pow(2,2))
4.0
4
Exercise
What is wrong with the following code?
In [24]: import math as m
[Link] 8/34
2/17/25, 3:56 PM Using Functions
for m in range(5):
print([Link](m, 2))
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[24], line 4
1 import math as m
3 for m in range(5):
----> 4 print([Link](m, 2))
import math as m
for i in range(5):
print([Link](i, 2))
0.0
1.0
4.0
9.0
16.0
Exercise Use the randint function from random to simulate the rolling of a die,
by printing a random integer from 1 to 6.
random module is used to generate random numbers
[Link](a, b) : return a random integer N such that a <= N <= b
In [28]: # Solution
from random import randint #import randint function only
for i in range(1,5):
print(randint(1,6)) #use a for loop to generate 4 random integers be
5
4
1
2
In [29]: #Example
import math
[Link](2)
Out[29]: 0.9092974268256817
[Link] 9/34
2/17/25, 3:56 PM Using Functions
2. import specific functions from a module. In this case you can use the function
name directly
from module_name import function_1,function_2,...
function_name()
In [30]: #Example
from math import sin
sin(2)
Out[30]: 0.9092974268256817
3. import everything from a module. If you're unsure what to import, you can import
everything. But it occupies more memory.
from module_name import *
function_name()
In [31]: #Example
from math import *
print(sin(2))
print(log(256,2))
0.9092974268256817
8.0
[Link] 10/34
2/17/25, 3:56 PM Using Functions
Built-in Functions
How to learn more about a function such as randint ?
There is a built-in function help for showing the docstring (documentation string).
help() is used to display the documentation of an object to help user understand
how it works.
In [23]: import random
help([Link]) # random must be imported before
?[Link]
Signature: [Link](a, b)
Docstring:
Return random integer in range [a, b], including both end points.
File: /opt/conda/lib/python3.11/[Link]
Type: method
[Link] 11/34
2/17/25, 3:56 PM Using Functions
NAME
random - Random variable generators.
MODULE REFERENCE
[Link]
DESCRIPTION
bytes
-----
uniform bytes (values between 0 and 255)
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation
CLASSES
_random.Random([Link])
Random
SystemRandom
[Link] 12/34
2/17/25, 3:56 PM Using Functions
class Random(_random.Random)
| Random(x=None)
|
| Random number generator base class used by bound module functions.
|
| Used to instantiate instances of Random to get generators that do
n't
| share state.
|
| Class Random can also be subclassed if you want to use a different
basic
| generator of your own devising: in that case, override the followi
ng
| methods: random(), seed(), getstate(), and setstate().
| Optionally, implement a getrandbits() method so that randrange()
| can cover arbitrarily large ranges.
|
| Method resolution order:
| Random
| _random.Random
| [Link]
|
| Methods defined here:
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for [Link]().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with repla
cement.
|
| If the relative weights or cumulative weights are not specifie
d,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
[Link] 13/34
2/17/25, 3:56 PM Using Functions
[Link] 14/34
2/17/25, 3:56 PM Using Functions
[Link] 15/34
2/17/25, 3:56 PM Using Functions
[Link] 16/34
2/17/25, 3:56 PM Using Functions
class SystemRandom(Random)
| SystemRandom(x=None)
|
| Alternate random number generator using sources provided
| by the operating system (such as /dev/urandom on Unix or
| CryptGenRandom on Windows).
|
| Not available on all systems (see [Link]() for details).
|
| Method resolution order:
| SystemRandom
| Random
| _random.Random
| [Link]
|
| Methods defined here:
|
| getrandbits(self, k)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| getstate = _notimplemented(self, *args, **kwds)
|
| randbytes(self, n)
| Generate n random bytes.
|
| random(self)
| Get the next random number in the range 0.0 <= X < 1.0.
|
| seed(self, *args, **kwds)
| Stub method. Not used for a system random number generator.
|
| setstate = _notimplemented(self, *args, **kwds)
|
| ------------------------------------------------------------------
----
| Methods inherited from Random:
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for [Link]().
[Link] 17/34
2/17/25, 3:56 PM Using Functions
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with repla
cement.
|
| If the relative weights or cumulative weights are not specifie
d,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * [Link](-x / beta)
| pdf(x) = --------------------------------------
| [Link](alpha) * beta ** alpha
|
| gauss(self, mu=0.0, sigma=1.0)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll
get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu=0.0, sigma=1.0)
[Link] 18/34
2/17/25, 3:56 PM Using Functions
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end poin
ts.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(stop) or range(start, stop[, s
tep]).
|
| Roughly equivalent to ``choice(range(start, stop, step))`` but
| supports arbitrarily large ranges and is optimized for common
cases.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence.
|
| Returns a new list containing elements from the population whi
le
| leaving the original population unchanged. The resulting list
is
| in selection order so that all sub-slices will also be valid r
andom
| samples. This allows raffle winners (the sample) to be partit
ioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If
the
| population contains repeats, then each occurrence is a possibl
e
| selection in the sample.
|
| Repeated elements can be specified one at a time or with the o
ptional
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for t
he
| population argument. This is especially fast and space effici
ent
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| shuffle(self, x)
| Shuffle list x in place, and return None.
|
| triangular(self, low=0.0, high=1.0, mode=None)
[Link] 19/34
2/17/25, 3:56 PM Using Functions
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limit
s,
| and having a given mode value in-between.
|
| [Link]
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on
rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi,
and
| kappa is the concentration parameter, which must be greater th
an or
| equal to zero. If kappa is equal to zero, this distribution r
educes
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ------------------------------------------------------------------
----
| Class methods inherited from Random:
|
| __init_subclass__(**kwargs) from [Link]
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/o
r
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ------------------------------------------------------------------
----
| Data descriptors inherited from Random:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ------------------------------------------------------------------
----
| Data and other attributes inherited from Random:
|
| VERSION = 3
|
| ------------------------------------------------------------------
----
| Static methods inherited from _random.Random:
[Link] 20/34
2/17/25, 3:56 PM Using Functions
|
| __new__(*args, **kwargs) from [Link]
| Create and return a new object. See help(type) for accurate s
ignature.
FUNCTIONS
betavariate(alpha, beta) method of Random instance
Beta distribution.
[Link] 21/34
2/17/25, 3:56 PM Using Functions
is equivalent to:
sample(range(10000000), 60)
[Link] 22/34
2/17/25, 3:56 PM Using Functions
For version 2 (the default), all of the bits are used if *a* is a
str,
bytes, or bytearray. For version 1 (provided for reproducing rand
om
sequences from older versions of Python), the algorithm for str an
d
bytes generates a narrower range of seeds.
[Link]
DATA
__all__ = ['Random', 'SystemRandom', 'betavariate', 'choice', 'choice
s...
FILE
/opt/conda/lib/python3.11/[Link]
[Link] 23/34
2/17/25, 3:56 PM Using Functions
In [25]: help(int)
[Link] 24/34
2/17/25, 3:56 PM Using Functions
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surround
ed
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer liter
al.
| >>> int('0b100', base=0)
| 4
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Default object formatter.
|
| __ge__(self, value, /)
| Return self>=value.
[Link] 25/34
2/17/25, 3:56 PM Using Functions
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use a
s an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
[Link] 26/34
2/17/25, 3:56 PM Using Functions
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
|
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| as_integer_ratio(self, /)
| Return integer ratio.
|
[Link] 27/34
2/17/25, 3:56 PM Using Functions
[Link] 28/34
2/17/25, 3:56 PM Using Functions
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder='big', *, signed=False) from [Link]
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing b
ytes.
| Bytes and bytearray are examples of built-in objects that suppor
t the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is
'big',
| the most significant byte is at the beginning of the byte array.
If
| byteorder is 'little', the most significant byte is at the end o
f the
| byte array. To request the native byte order of the host syste
m, use
| `[Link]' as the byte order value. Default is to use 'bi
g'.
| signed
| Indicates whether two's complement is used to represent the inte
ger.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from [Link]
| Create and return a new object. See help(type) for accurate signa
ture.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
[Link] 29/34
2/17/25, 3:56 PM Using Functions
[Link] 30/34
2/17/25, 3:56 PM Using Functions
Out[35]: ['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BaseExceptionGroup',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
'BytesWarning',
'ChildProcessError',
'ConnectionAbortedError',
'ConnectionError',
'ConnectionRefusedError',
'ConnectionResetError',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EncodingWarning',
'EnvironmentError',
'Exception',
'ExceptionGroup',
'False',
'FileExistsError',
'FileNotFoundError',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'InterruptedError',
'IsADirectoryError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'ModuleNotFoundError',
'NameError',
'None',
'NotADirectoryError',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'PermissionError',
'ProcessLookupError',
'RecursionError',
'ReferenceError',
'ResourceWarning',
'RuntimeError',
'RuntimeWarning',
'StopAsyncIteration',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
[Link] 31/34
2/17/25, 3:56 PM Using Functions
'TabError',
'TimeoutError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'ZeroDivisionError',
'__IPYTHON__',
'__build_class__',
'__debug__',
'__doc__',
'__import__',
'__loader__',
'__name__',
'__package__',
'__pybind11_internals_v4_gcc_libstdcpp_cxxabi1018__',
'__spec__',
'abs',
'aiter',
'all',
'anext',
'any',
'ascii',
'bin',
'bool',
'breakpoint',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'display',
'divmod',
'enumerate',
'eval',
'exec',
'execfile',
'filter',
'float',
'format',
'frozenset',
'get_ipython',
'getattr',
'globals',
'hasattr',
'hash',
[Link] 32/34
2/17/25, 3:56 PM Using Functions
'help',
'hex',
'id',
'input',
'int',
'isinstance',
'issubclass',
'iter',
'len',
'license',
'list',
'locals',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'range',
'repr',
'reversed',
'round',
'runfile',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']
Exercise
We can also call dir without arguments. What does it print?
{hint}
Try `help(dir)` or `dir?` in jupyter notebook.
In [1]: dir()
[Link] 33/34
2/17/25, 3:56 PM Using Functions
Out[1]: ['In',
'Out',
'_',
'__',
'___',
'__builtin__',
'__builtins__',
'__doc__',
'__loader__',
'__name__',
'__package__',
'__session__',
'__spec__',
'_dh',
'_i',
'_i1',
'_ih',
'_ii',
'_iii',
'_oh',
'exit',
'get_ipython',
'open',
'quit']
In [37]: dir?
Docstring:
dir([object]) -> list of strings
In [ ]:
[Link] 34/34