0% found this document useful (0 votes)
5 views34 pages

Understanding Functions in Programming

The document provides an introduction to using functions in programming, explaining the concepts of functions, modules, and packages. It covers how to define and call functions, the difference between local and global variables, and how to import functions from modules. Additionally, it discusses potential name collisions when importing and demonstrates how to avoid them by using aliases.

Uploaded by

horace23vt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views34 pages

Understanding Functions in Programming

The document provides an introduction to using functions in programming, explaining the concepts of functions, modules, and packages. It covers how to define and call functions, the difference between local and global variables, and how to import functions from modules. Additionally, it discusses potential name collisions when importing and demonstrates how to avoid them by using aliases.

Uploaded by

horace23vt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2/17/25, 3:56 PM Using Functions

Using Functions
CS1302 Introduction to Computer Programming

In [1]: %reload_ext divewidgets

# Set LLM alias


%load_ext jupyter_ai
%ai update chatgpt dive:chat

Out[1]: Updated target of alias chatgpt

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}

*Code reuse* gives the code an elegant *structure* that


- can be executed efficiently by a computer, and
- *interpreted* easily by a programmer.

How to repeat execution at different times, in different programs, and in slightly


different ways?
-We use functions
Some basic concepts before introducing functions
Function vs Module vs Package/Library
Function is a block of code that can perform specific task
Module is a collection of functions and global variables
Package/Library is a collection of modules
member operator .
if we want to use a function inside a module, we need to use member operator,
e.g., module_A.function_B
[Link] 1/34
2/17/25, 3:56 PM Using Functions

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'

A function has three components:


function name
arguments or parameters (optional)
return data (optional)
Let's see the following example which defines a function calculate_area()

In [10]: #in this example, PI is a global variable,but area is a local variable


import math
PI = 3.14

def calculate_area(radius):
area=[Link]*radius**2
return area

print(calculate_area(2.6)) #this is function call


print(PI) #this is correct because PI is a global variable
print(area) #this is wrong cause area is defined in calculate_area, and c

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

NameError: name 'area' is not defined

Local variable vs Global variable


[Link] 2/34
2/17/25, 3:56 PM Using Functions

A local variable is a variable declared inside a function. It can be only accessed


inside a function.
A global variable is a variable declared outside of the function or in global scope.
This means that a global variable can be accessed inside or outside of the
function.
In the above code, PI is a global variable and can be used anywhere in the program.
But area is a local variable which can only be used in function
calculate_area() .

Now let's learn how to use functions written by others


How to calculate the logarithm?
There is no arithmetic operator for logarithm.
Do we have to implement it ourselves?
-no, many functions have been implemented by others, we can just use them
We can use the function log from the math module:
math is a module that you can use for mathematical tasks

In order to use functions in math module, we need to import them


In [11]: from math import log #this is how we import a function from a module
x=log(256, 2) # log base 2 of 256
print(x)

8.0

The above computes the base-$2$ logarithm, $\log_2(256)$.


Like functions in mathematics $y=f(x)$, a computer function log
is called/invoked with some input arguments (256, 2) following the function,
and
returns an output value computed from the input arguments.
Unlike mathematical functions:
y=f(); this is wrong in math
A computer function may require no arguments, but we still need to call it with
() .

In [13]: input("Please input an integer value: ") # calling the input() function

Out[13]: '10'

An argument of a function call can be any expression.


In [14]: print('1st input:',input(),'2nd input',input())

[Link] 3/34
2/17/25, 3:56 PM Using Functions

1st input: 1 2nd input 2

{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`

Why not implement logarithm yourself?


The function from standard library is efficiently implemented and thoroughly
tested/documented.
Knowing what a function does is often insufficient for an efficient
implementation.
(See how to calculate logarithm as an example.)
Indeed, the math library does not implement log itself:
CPython implementation detail: The math module consists mostly
of thin wrappers around the platform C math library functions. - pydoc
last paragraph
(See the source code wrapper for log .)
Exercise
What is a function in programming?
Solution: A function is a block of code that performs a specific task. You can pass
data, known as parameters, into a function. A function can return data as a result.
In [6]: %%ai chatgpt -f text
In one paragraph, explain what is a function in programming.

Out[6]: A function in programming is a block of code that performs a specific ta


sk and can be reused throughout a program. It typically takes in input,
known as arguments or parameters, processes the input, and returns outpu
t. Functions are designed to be self-contained, modular, and reusable, a
llowing developers to organize and structure their code in a logical and
efficient manner. By encapsulating a specific piece of functionality wit
hin a function, programmers can call the function multiple times from di
fferent parts of the program, passing in different inputs to achieve var
ying results, making their code more concise, readable, and maintainabl
e.

[Link] 4/34
2/17/25, 3:56 PM Using Functions

Import Functions from Modules


Why import functions?
To tell computer where the function is. The computer doesn't load all the functions
when it starts up, otherwise it takes up too much memory.
How to import functions?
We can use the import statement to import multiple functions into the program
global frame.
Syntax:
from module_name import function_1, function_2,...

In [14]: from math import log10, ceil, floor


x = 1234
print('Number of digits of x:', floor(log10(x))+1)

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)))

0.50, 0.50, 1.00

What if different packages define the same function?


[Link] 5/34
2/17/25, 3:56 PM Using Functions

Python has built-in function pow()


Math also has a function pow()
In [18]: %%ai chatgpt -f text
In one paragraph, explain what is the difference between built-in functio

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 [18]: %%optlite -h 300


print('{}'.format(pow(-1,2)))
print('{:.2f}'.format(pow(-1,1/2)))
from math import *
#after import, the system will use pow() defined in math
print('{}'.format(pow(-1,2)))
print('{:.2f}'.format(pow(-1,1/2)))

Out[18]: OPTWidget(value=None, height=300, script="print('{}'.format(pow(-1,2)))


\nprint('{:.2f}'.format(pow(-1,1/2)))\n…

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))

ValueError: math domain error

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

In [20]: %%optlite -h 250


import math
#the above command only import math library but not functions,
#so we have to use [Link]() when we call functions
print('{:.2f}, {:.2f}'.format([Link](-1,2),pow(-1,1/2)))

Out[20]: OPTWidget(value=None, height=250, script="import math\n#the above comman


d only import math library but not fun…

Can we shorten a name?


The name of a library can be very long and there can be a hierarchical structure as
well.
E.g., to plot a sequence using pyplot module from matplotlib package (you
don't need to know how matplotlib works):
In [21]: %matplotlib inline
import [Link]
[Link]([4,3,2,1])
[Link](r'$x_n$')
[Link](r'$n$')
[Link]('A sequence of numbers')
[Link]()

It is common to rename [Link] as plt :


Syntax:
#method 1
import package.module_name as short_name

[Link] 7/34
2/17/25, 3:56 PM Using Functions

#method 2
from package_name import module_name as short_name

In [23]: %matplotlib inline


import [Link] as plt
#from matplotlib import pyplot as plt #equivalent to above
[Link]([4,3,2,1])
[Link](r'$x_n$')
[Link](r'$n$')
[Link]('A sequence of numbers')
[Link]()

We can also rename a function as we import it to avoid name collision:


In [23]: #from math import pow as fpow
#fpow(2,2),pow(2,2)
from math import pow
print(pow(2,2))

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))

AttributeError: 'int' object has no attribute 'pow'

In [25]: #Name collision. We can change m to another variable

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

A short summary of how to import


1. import the package name directly. In this case you need to point out the module
name when you call a function
import module_name
module_name.function_name()

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

4. rename a module if it has a long name


#method 1
import package.module_name as short_name
#method 2
from package_name import module_name as short_name

In [32]: #in this example, matplotlib is a package, pyplot is a module


#stem() ylabel() are functions
%matplotlib inline
import [Link] as plt
#from matplotlib import pyplot as plt #equivalent to the above line
[Link]([4,3,2,1])
[Link](r'$x_n$')
[Link](r'$n$')
[Link]('A sequence of numbers')
[Link]()

[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]

Help on method randint in module random:

randint(a, b) method of [Link] instance


Return random integer in range [a, b], including both end points.

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

In [24]: help(random) # can also show the docstring of a module

[Link] 11/34
2/17/25, 3:56 PM Using Functions

Help on module random:

NAME
random - Random variable generators.

MODULE REFERENCE
[Link]

The following documentation is automatically generated from the Python


source files. It may be incomplete, incorrect or include features tha
t
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.

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

distributions on the real line:


------------------------------
uniform
triangular
normal (Gaussian)
lognormal
negative exponential
gamma
beta
pareto
Weibull

distributions on the circle (angles 0 to 2pi)


---------------------------------------------
circular uniform
von Mises

General notes on the underlying Mersenne Twister core generator:

* The period is 2**19937-1.


* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python
step,
and is, therefore, threadsafe.

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

| 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.
|
| getstate(self)
| Return internal state; can be passed to setstate() later.
|
| 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)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randbytes(self, n)
| Generate n random bytes.
|
| 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.
|

[Link] 14/34
2/17/25, 3:56 PM Using Functions

| 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)
|
| seed(self, a=None, version=2)
| Initialize internal state from a seed.
|
| The only supported seed types are None, int, float,
| str, bytes, and bytearray.
|
| None or no argument seeds from current time or from an operati
ng
| system specific randomness source if available.
|
| If *a* is an int, all bits are used.
|
| For version 2 (the default), all of the bits are used if *a* i
s a str,
| bytes, or bytearray. For version 1 (provided for reproducing
random
| sequences from older versions of Python), the algorithm for st
r and
| bytes generates a narrower range of seeds.
|
| setstate(self, state)
| Restore internal state from object returned by getstate().
|
| shuffle(self, x)
| Shuffle list x in place, and return None.
|

[Link] 15/34
2/17/25, 3:56 PM Using Functions

| triangular(self, low=0.0, high=1.0, mode=None)


| 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 defined here:
|
| __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 defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ------------------------------------------------------------------
----
| Data and other attributes defined here:
|
| VERSION = 3
|
| ------------------------------------------------------------------
----

[Link] 16/34
2/17/25, 3:56 PM Using Functions

| Methods inherited from _random.Random:


|
| getrandbits(self, k, /)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| random(self, /)
| random() -> x in the interval [0, 1).
|
| ------------------------------------------------------------------
----
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) from [Link]
| Create and return a new object. See help(type) for accurate s
ignature.

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.

Conditions on the parameters are alpha > 0 and beta > 0.


Returned values range between 0 and 1.

choice(seq) method of Random instance


Choose a random element from a non-empty sequence.

choices(population, weights=None, *, cum_weights=None, k=1) method of


Random instance
Return a k sized list of population elements chosen with replaceme
nt.

If the relative weights or cumulative weights are not specified,


the selections are made with equal probability.

expovariate(lambd) method of Random instance


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(alpha, beta) method of Random instance


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(mu=0.0, sigma=1.0) method of Random instance


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.

getrandbits(k, /) method of Random instance


getrandbits(k) -> x. Generates an int with k random bits.

getstate() method of Random instance


Return internal state; can be passed to setstate() later.

lognormvariate(mu, sigma) method of Random instance


Log normal distribution.

[Link] 21/34
2/17/25, 3:56 PM Using Functions

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(mu=0.0, sigma=1.0) method of Random instance


Normal distribution.

mu is the mean, and sigma is the standard deviation.

paretovariate(alpha) method of Random instance


Pareto distribution. alpha is the shape parameter.

randbytes(n) method of Random instance


Generate n random bytes.

randint(a, b) method of Random instance


Return random integer in range [a, b], including both end points.

random() method of Random instance


random() -> x in the interval [0, 1).

randrange(start, stop=None, step=1) method of Random instance


Choose a random item from range(stop) or range(start, stop[, ste
p]).

Roughly equivalent to ``choice(range(start, stop, step))`` but


supports arbitrarily large ranges and is optimized for common case
s.

sample(population, k, *, counts=None) method of Random instance


Chooses k unique random elements from a population sequence.

Returns a new list containing elements from the population while


leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid rando
m
samples. This allows raffle winners (the sample) to be partitione
d
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 possible
selection in the sample.

Repeated elements can be specified one at a time or with the optio


nal
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 the


population argument. This is especially fast and space efficient
for sampling from a large population:

sample(range(10000000), 60)

[Link] 22/34
2/17/25, 3:56 PM Using Functions

seed(a=None, version=2) method of Random instance


Initialize internal state from a seed.

The only supported seed types are None, int, float,


str, bytes, and bytearray.

None or no argument seeds from current time or from an operating


system specific randomness source if available.

If *a* is an int, all bits are used.

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.

setstate(state) method of Random instance


Restore internal state from object returned by getstate().

shuffle(x) method of Random instance


Shuffle list x in place, and return None.

triangular(low=0.0, high=1.0, mode=None) method of Random instance


Triangular distribution.

Continuous distribution bounded by given lower and upper limits,


and having a given mode value in-between.

[Link]

uniform(a, b) method of Random instance


Get a random number in the range [a, b) or [a, b] depending on rou
nding.

vonmisesvariate(mu, kappa) method of Random instance


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 than o
r
equal to zero. If kappa is equal to zero, this distribution reduc
es
to a uniform random angle over the range 0 to 2*pi.

weibullvariate(alpha, beta) method of Random instance


Weibull distribution.

alpha is the scale parameter and beta is the shape parameter.

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

Help on class int in module builtins:

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

| Return a pair of integers, whose ratio is exactly equal to the ori


ginal int
| and with a positive denominator.
|
| >>> (10).as_integer_ratio()
| (10, 1)
| >>> (-10).as_integer_ratio()
| (-10, 1)
| >>> (0).as_integer_ratio()
| (0, 1)
|
| bit_count(self, /)
| Number of ones in the binary representation of the absolute value
of self.
|
| Also known as the population count.
|
| >>> bin(13)
| '0b1101'
| >>> (13).bit_count()
| 3
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| to_bytes(self, /, length=1, byteorder='big', *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if th
e
| integer is not representable with the given number of bytes. De
fault
| is length 1.
| 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
| Determines whether two's complement is used to represent the int
eger.
| If signed is False and a negative integer is given, an OverflowE
rror
| is raised.
|

[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

Does built-in functions belong to a module?


Indeed, every function must come from a module. built-in functions are from
_builtin_ module
In [34]: __builtin__.print('I am from the __builtin__ module.')
print('I am from the __builtin__ module.') #print() function is from _bui

[Link] 29/34
2/17/25, 3:56 PM Using Functions

I am from the __builtin__ module.


I am from the __builtin__ module.

__builtin__ module is automatically loaded because it provides functions that


are commonly use for all programs.
How to list everything in a module?
We can use the built-in function dir (directory).
dir(module_name) lists all the attributes and functions of an object (say functions ,
modules, strings)
In [35]: dir(__builtin__)

[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

If called without an argument, return the names in the current scope.


Else, return an alphabetized list of names comprising (some of) the attrib
utes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
Type: builtin_function_or_method

In [ ]:

[Link] 34/34

You might also like