These are some basic exercices to get used to Python.
Declare and assign some variables:
a = 3
b = a + 3
c = a * 2.5
Then check its type with type(a). See what happens when you use an udeclared variable. What value does it take?
In [ ]:
Remember than lists and other mutable variables behave as pointers. Try to predict the result of this:
a = [1,2,3]
b = a
a.append(4)
print(a)
print(b)
In [ ]:
a = [1,2,3]
b = a
a.append(4)
print(a)
print(b)
Try to predict and understand what this does:
a=5; b=7
a, b = b, a
a,b,c = range(3)
a, b, c = range(5)
a, b, *c = range(5)
In [ ]:
a,*b, c = range(5)
a,b,c
Be quiet, relax and type: import this
In [ ]:
Floating Point arithmetics
As scientists we should be specially aware of an advanced topic, floating point arithmetic. This is a general topic for all computer languages, but it is worth remembering it. Try to predict and understand the result of these line:
50 * 1/50 == 1/50 * 50, 49 * 1/49 == 1/49 * 49
In [1]:
50 * 1/50 , 1/50 * 50, 49 * 1/49 , 1/49 * 49
Out[1]:
In [2]:
49 * 1/49 == 1/49 * 49
Out[2]:
If you really need to work with exact arithmetic, Python offers a couple of solutions, that we will not explore further here. Try this:
In [ ]:
import fractions
50*fractions.Fraction(1,50) == 49*fractions.Fraction(1,49)
A similar problem is occurs here. What do you expect this to return?
In [ ]:
(1.2-1)*10
Now correct the previous input using the fractions module. You could also use the decimals module, this way:
In [1]:
import decimal
num = decimal.Decimal('1.2')
int((num-1)*10)
Out[1]:
This is mainly to show that there are modules for almost everything. The fractions and decimal modules are not part of this course, just an anecdote.
In [ ]: