Modules and Packages (libraries)
Contents
Modules and Packages (libraries)¶
Modules and libraries are blocks of code that we can import in our main program. Through that code becomes reusable and we can save time etc. Furthermore we can use modules and libraries without dealing with (or even without understanding) the inside of the code.
Writing own modules¶
Next to using libraries provided by other programmers, we can also write our own modules. Python Code is written as plain text and likewise a module is just a plain text file.
In order to use code from a module, the code itself has to be callable, thus stored as an object like a variable, a function or a class (we’ll learn about that later).
For example we could copy&paste the functions from the functions chapter (also in the hidden cell below) into a new text file called my_module.py
. If this file is placed in the folder of our project, we can import it directly.
def stein_grammar(data):
'''Process a text according to the grammar of Gertrude Stein.'''
import spacy
nlp = spacy.load('en_core_web_sm')
# Analyze text with the spacy object
doc = nlp(data)
stein = '' # Empty string for the new text.
# Remove all unwanted tokens
for token in doc:
if token.pos_ not in ['NOUN', 'ADJ'] and str(token) not in [',', '!', '?']:
# Add the token,
# with a leading space if the token is not a PUNCT (or stein is empty)
if token.pos_ != 'PUNCT' and stein != '':
stein += ' '
stein += str(token)
# Return processed input
return stein
def burroughs_replacements(txt):
# txt is a local variable that does not
# conflict with the global 'txt' variable
txt = txt.replace(' is ', ' ').replace(' to be ', ' ')
txt = txt.replace(' the ', ' a ').replace('The ', 'A ')
txt = txt.replace(' or ', ' and ').replace('Or ', 'And ')
return txt
def translate_poem(text):
# Original author: Julia Nakotte: file.read() (2021)
# Adapted to a working translate library
# Added return functionality
from textblob import TextBlob
from textblob import Word
import translators as ts
import random
output = '' # Store result instead of printing it
for a in range(3):
title = ts.google(random.choice(text.split()), to_language = "en")
titel = ts.google((f"{title}"), to_language = "de")
output += "\033[1m" + f"{titel}" + "\033[0m" + "\n"
for t in range(5):
RandomN = random.choice([w for (w, pos) in TextBlob(text).tags if pos[1] == "N"])
RandomV = random.choice([w for (w, pos) in TextBlob(text).tags if pos[0] == "V"])
RandomA = random.choice([w for (w, pos) in TextBlob(text).tags if pos[0] == "J"])
RandomAv = random.choice([w for (w, pos) in TextBlob(text).tags if pos[0] == "R"])
RandomP = random.choice([w for (w, pos) in TextBlob(text).tags if pos[0] == "P"])
wörter = RandomN, RandomV, RandomA, RandomAv, RandomP # , "\n" moved to the end
poem = ts.google(" ".join(random.sample(wörter, k = len(wörter))), to_language = "en")
uta = ts.google((f"{poem}"), to_language = "ja")
gedicht = ts.google((f"{uta}"), to_language = "de")
output += f"{gedicht}\n"
output += 6*"\n"
return output
def shuffle_nouns(txt):
from nltk import pos_tag, word_tokenize
import random
# Store words + tags in a list
# like [('The', 'DT'), ('quick', 'JJ'), ('brown', 'NN')]
tags = pos_tag(word_tokenize(txt))
# Store all nouns in a new list
nouns = [word[0] for word in tags if word[1] == 'NN']
# Shuffle nouns
random.shuffle(nouns)
# Empty variable for the output
out = ''
for word, tag in tags:
# Add a space if the word is alnum
if word.isalnum():
out += ' '
# Replace noun
if tag == 'NN':
# pick the last noun from the shuffled list
# and remove it from the list
word = nouns.pop()
# Add the word (or punct) to the output
out += word
out = out.strip()
return out
Import modules¶
import my_module
Now we have access to the code inside my_module.py
.
The name of the module is like an address and we have to use that, before we can specify what code from that location/ file we want to access.
This is done with a so called dot notation: name_of_module.name_of_object
.
To see what’s inside a package we can use the function dir()
:
dir(my_module)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'burroughs_replacements',
'shuffle_nouns',
'stein_grammar',
'translate_poem']
All the objects enclosed in __ are built-ins from Python, the functions below that are ours.
txt = 'The lazy programmer jumps over the quick brown fox jumps over the lazy programmer jumps over the fire fox.'
# We can call the objects via dot notation.
my_module.burroughs_replacements(txt)
'A lazy programmer jumps over a quick brown fox jumps over a lazy programmer jumps over a fire fox.'
my_module.stein_grammar(txt)
'The jumps over the jumps over the jumps over the.'
my_module
.
Import specific objects of a module/ library¶
from my_module import shuffle_nouns
Then we can use this function as if we had written it inside our main program, thus without dot-notation.
shuffle_nouns(txt)
'The lazy brown jumps over the quick fox fox jumps over the lazy programmer jumps over the programmer fire.'
Import a module or a single object and assign it to a new name¶
We can change the name of our imports if we want to. This can save time later as we don’t have to type the whole names inside our program.
import my_module as mm
mm.shuffle_nouns(txt)
'The lazy programmer jumps over the quick fox brown jumps over the lazy fire jumps over the programmer fox.'
from my_module import burroughs_replacements as burroughs
burroughs(txt)
'A lazy programmer jumps over a quick brown fox jumps over a lazy programmer jumps over a fire fox.'
Pre-installed modules¶
When we install Python, a lot of modules are installed as well. For example the module random
.
import random
So far we don’t know what’s inside the random module so we don’t know what we can call. We can get an overview with dir()
again.
dir(random)
['BPF',
'LOG4',
'NV_MAGICCONST',
'RECIP_BPF',
'Random',
'SG_MAGICCONST',
'SystemRandom',
'TWOPI',
'_Sequence',
'_Set',
'__all__',
'__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_accumulate',
'_acos',
'_bisect',
'_ceil',
'_cos',
'_e',
'_exp',
'_floor',
'_inst',
'_log',
'_os',
'_pi',
'_random',
'_repeat',
'_sha512',
'_sin',
'_sqrt',
'_test',
'_test_generator',
'_urandom',
'_warn',
'betavariate',
'choice',
'choices',
'expovariate',
'gammavariate',
'gauss',
'getrandbits',
'getstate',
'lognormvariate',
'normalvariate',
'paretovariate',
'randbytes',
'randint',
'random',
'randrange',
'sample',
'seed',
'setstate',
'shuffle',
'triangular',
'uniform',
'vonmisesvariate',
'weibullvariate']
help()¶
We can get access to more information with help()
.
print(help(random))
Help on module random:
NAME
random - Random variable generators.
MODULE REFERENCE
https://docs.python.org/3.8/library/random
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
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(builtins.object)
Random
SystemRandom
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 don'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 following
| 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
| builtins.object
|
| Methods defined here:
|
| __getstate__(self)
| # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
| # longer called; we leave it here because it has been here since random was
| # rewritten back in 2001 and why risk breaking something.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __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 replacement.
|
| If the relative weights or cumulative weights are not specified,
| 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) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu, sigma)
| 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, sigma)
| 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 points.
|
| randrange(self, start, stop=None, step=1, _int=<class 'int'>)
| Choose a random item from range(start, stop[, step]).
|
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.
|
| sample(self, population, k)
| Chooses k unique random elements from a population sequence or set.
|
| 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 random
| samples. This allows raffle winners (the sample) to be partitioned
| 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.
|
| To choose a sample in a range of integers, use range as an argument.
| This is especially fast and space efficient for sampling from a
| large population: sample(range(10000000), 60)
|
| seed(self, a=None, version=2)
| Initialize internal state from hashable object.
|
| 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 random
| sequences from older versions of Python), the algorithm for str and
| bytes generates a narrower range of seeds.
|
| setstate(self, state)
| Restore internal state from object returned by getstate().
|
| shuffle(self, x, random=None)
| Shuffle list x in place, and return None.
|
| Optional argument random is a 0-argument function returning a
| random float in [0.0, 1.0); if it is the default None, the
| standard random.random will be used.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| 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 than or
| equal to zero. If kappa is equal to zero, this distribution reduces
| 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 builtins.type
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| 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 (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Methods inherited from _random.Random:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| 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 builtins.type
| Create and return a new object. See help(type) for accurate signature.
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 os.urandom() for details).
|
| Method resolution order:
| SystemRandom
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| getrandbits(self, k)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| getstate = _notimplemented(self, *args, **kwds)
|
| random(self)
| Get the next random number in the range [0.0, 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)
| # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
| # longer called; we leave it here because it has been here since random was
| # rewritten back in 2001 and why risk breaking something.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __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 replacement.
|
| If the relative weights or cumulative weights are not specified,
| 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) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu, sigma)
| 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, sigma)
| 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 points.
|
| randrange(self, start, stop=None, step=1, _int=<class 'int'>)
| Choose a random item from range(start, stop[, step]).
|
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.
|
| sample(self, population, k)
| Chooses k unique random elements from a population sequence or set.
|
| 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 random
| samples. This allows raffle winners (the sample) to be partitioned
| 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.
|
| To choose a sample in a range of integers, use range as an argument.
| This is especially fast and space efficient for sampling from a
| large population: sample(range(10000000), 60)
|
| shuffle(self, x, random=None)
| Shuffle list x in place, and return None.
|
| Optional argument random is a 0-argument function returning a
| random float in [0.0, 1.0); if it is the default None, the
| standard random.random will be used.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| 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 than or
| equal to zero. If kappa is equal to zero, this distribution reduces
| 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 builtins.type
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| 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 (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Random:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Methods inherited from _random.Random:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
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 replacement.
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) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha
gauss(mu, sigma) 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.
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, sigma) 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.
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, _int=<class 'int'>) method of Random instance
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
sample(population, k) method of Random instance
Chooses k unique random elements from a population sequence or set.
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 random
samples. This allows raffle winners (the sample) to be partitioned
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.
To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(range(10000000), 60)
seed(a=None, version=2) method of Random instance
Initialize internal state from hashable object.
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 random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.
setstate(state) method of Random instance
Restore internal state from object returned by getstate().
shuffle(x, random=None) method of Random instance
Shuffle list x in place, and return None.
Optional argument random is a 0-argument function returning a
random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.
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.
http://en.wikipedia.org/wiki/Triangular_distribution
uniform(a, b) method of Random instance
Get a random number in the range [a, b) or [a, b] depending on rounding.
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 or
equal to zero. If kappa is equal to zero, this distribution reduces
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', 'seed', 'random', 'uniform', 'randint', 'choice',...
FILE
/usr/lib/python3.8/random.py
None
Location of modules¶
We can inspect the module with the output of help, but let’s view the module reference online:
MODULE REFERENCE https://docs.python.org/3.8/library/random
The first thing is a link to the
Source code: Lib/random.py
When we execute the statement
import random
we load the code from random.py
as we have done with the code from my_module.py
.
Of course we don’t load it from the web, instead we have a local copy on our machine, which was made during the installation of Python.
You can find it through the
FILE /usr/lib/python3.8/random.py
reference via
random.__file__
Some functions of random¶
print(random.randint(0,3))
1
We can use
random.seed()
to initiate the random value generator, so that each time we have the same sequence of random values.
Commonly we use an integer as input for seed()
, but it’s for example possible to use a string
as well (which will be converted to int).
random.seed(0)
print(random.randint(-1e4,1e4))
random.seed(0)
print(random.randint(-1e4,1e4))
2623
2623
With
random.choice()
we can pick a random item of a sequence (a list
for example).
fruits = ['apple', 'banana', 'coconut']
print(random.choice(fruits))
banana
With
random.shuffle(list_)
we can shuffle a list in place (no return).
random.shuffle(fruits)
for f in fruits:
print(f)
coconut
banana
apple
Installation of external libraries¶
Next to pre-installed libraries we can install external libraries.
The official repository for libraries is the Python Package Index https://pypi.org/
The recommended way to install external libraries is via Pythons package installer pip, except you work in a conda environment. Then it’s recommended to first try it with condas package index.
Executing in an activated environment
# Install a package via conda
conda install <name of the package>
If that does not work, make sure to have pip installed in your activated environment
# Install pip via conda
conda install pip
# Install a package with pip
pip install <name of the package>
»Module«, »Package« or »Library«?¶
(This is actually not that important.) In general module
is used for single files with .py
suffix that contain some code which can be imported. A package
is a directory (folder) with commonly several modules that work together as a larger thing. Commonly packages are called libraries. On the other hand random.py
is just a single file, so a module, but it’s also called a library.