Py
Py
Docstrings
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
When we called help(print), we saw that the print function has several optional
arguments. For example, we can specify a value for sep to put some special string
in between our printed arguments:
By default, max returns the largest of its arguments. But if we pass in a function
using the optional key argument, it returns the argument x that maximizes key(x)
(aka the 'argmax').
def mod_5(x):
"""Return the remainder of x after dividing by 5"""
return x % 5
print(
'Which number is biggest?',
max(100, 51, 14),
'Which number is the biggest modulo 5?',
max(100, 51, 14, key=mod_5),
sep='\n',
)
Which number is biggest?
100
Which number is the biggest modulo 5?
14
As you've seen, ndigits=-1 rounds to the nearest 10, ndigits=-2 rounds to the
nearest 100 and so on. Where might this be useful? Suppose we're dealing with large
numbers:
We probably don't care whether it's really 338,424, or 338,425, or 338,177. All
those digits of accuracy are just distracting. We can chop them off by calling
round() with ndigits=-3:
What are the first three planets? We can answer this question using slicing:
planets[0:3]
['Mercury', 'Venus', 'Earth']
planets[:3]
['Mercury', 'Venus', 'Earth']
planets[3:]
['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
sum(primes)
max(primes)
we can use the in operator to determine whether a list contains a particular value:
# Is Earth a planet?
"Earth" in planets
True
Tuples are almost exactly the same as lists. They differ in just two ways.
1: The syntax for creating them uses parentheses instead of square brackets
t = (1, 2, 3)
Tuples are often used for functions that have multiple return values.
For example, the as_integer_ratio() method of float objects returns a numerator and
a denominator in the form of a tuple:
x = 0.125
x.as_integer_ratio()
(1, 8)
'Pluto\'s a planet!'
"Pluto's a planet!"
In addition, Python's triple quote syntax for strings lets us include newlines
literally (i.e. by just hitting 'Enter' on our keyboard, rather than using the
special '\n' sequence). We've already seen this in the docstrings we use to
document our functions, but we can use them anywhere we want to define a string.
triplequoted_hello = """hello
world"""
print(triplequoted_hello)
triplequoted_hello == hello
hello
world
True
But a major way in which they differ from lists is that they are immutable. We
can't modify them.
planet[0] = 'B'
# planet.append doesn't work either
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_19/2683731249.py in <module>
----> 1 planet[0] = 'B'
2 # planet.append doesn't work either
datestr = '1956-01-31'
year, month, day = datestr.split('-')
str.join() takes us in the other direction, sewing a list of strings up into one
long string, using the string it was called on as a separator.
position = 9
"{}, you'll always be the {}th planet to me.".format(planet, position)
"Pluto, you'll always be the 9th planet to me."
Dictionaries are a built-in Python data structure for mapping keys to values.
numbers = {'one':1, 'two':2, 'three':3}
We can access a collection of all the keys or all the values with dict.keys() and
dict.values(), respectively.
The very useful dict.items() method lets us iterate over the keys and values of a
dictionary simultaneously. (In Python jargon, an item refers to a key, value pair)
import math as mt
mt.pi
Wouldn't it be great if we could refer to all the variables in the math module by
themselves? i.e. if we could just refer to pi instead of math.pi or mt.pi? Good
news: we can do that.
See Also
--------
numpy.ravel : equivalent function
rolls + 10
array([13, 14, 13, 14, 15, 15, 12, 11, 13, 13])
import tensorflow as tf
# Create two constants, each with value 1
a = tf.constant(1)
b = tf.constant(1)
# Add them together to get...
a + b
<tf.Tensor: shape=(), dtype=int32, numpy=2>
a symbolic handle to one of the outputs of an Operation. It does not hold the
values of that operation's output, but instead provides a means of computing those
values in a TensorFlow tf.Session.
It's important just to be aware of the fact that this sort of thing is possible and
that libraries will often use operator overloading in non-obvious or magical-
seeming ways.
Understanding how Python's operators work when applied to ints, strings, and lists
is no guarantee that you'll be able to immediately understand what they do when
applied to a tensorflow Tensor, or a numpy ndarray, or a pandas DataFrame.
Once you've had a little taste of DataFrames, for example, an expression like the
one below starts to look appealingly intuitive: