Variables (such as the object with name a
in the examples below) are created through assignment of a value. We can check the type of the variable using the type()
function:
a = 10
type(a)
int
a = 3.14 # decimal point present makes this a float type
type(a)
float
a = 'Python' # single or double quotes define a string
type(a)
str
a = (1, 2, 3) # tuple: round brackets
type(a)
tuple
a = ['a', 2, 3.14] # list: square brackets
type(a)
list
Large/small values, e.g. $a = 2.1 \times 10^{6}$
a = 2.1e-6
a
2.1e-06
a = 10
b = 3
c = a + b
To inspect an object, we can just type its name if it is in the last line of a notebook cell:
c
13
The print()
function can be used to send information to the standard output (typically the display):
print('The value of c is:', c)
The value of c is: 13
a - b
7
a * b
30
a / b
3.3333333333333335
In Python 3, if we divide two int
variables, we are going to get float
:
5/2
2.5
a = 5
b = 3
a ** b # Common mistake to write a^b
125
Other "more complicated" operations generally live in math
or numpy
. Before math
can be used, it must be imported.
import math
All functions living in math
or any other module, can be accessed using .
operator.
theta = 3.14159 # theta is approximately pi
math.sin(theta)
2.65358979335273e-06
math.cos(theta)
-0.9999999999964793
math.sin(math.pi/2)
1.0
a = 10
math.log10(a)
1.0
math.log(math.e) # natural log
1.0
A collection of values can be represented using lists and tuples.
a = [1, 2, 3, 5.1e4] # list -> square bracket
a
[1, 2, 3, 51000.0]
b = (1, 2, 3, 5.1e4) # tuple -> round bracket
b
(1, 2, 3, 51000.0)
a[0] # the first element
1
a[0] = 5
a
[5, 2, 3, 51000.0]
b[3] # the last element
51000.0
Alternatively -1
can be used as an index to get the last element
a[-1]
51000.0
len(a)
4
len(b)
4
What is the difference between list and tuple? Tuples are not mutable.
b[2] = 3
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[29], line 1 ----> 1 b[2] = 3 TypeError: 'tuple' object does not support item assignment
If we have a point which is defined as a tuple and want to unpack the values into x, y, and z, we can write:
point = (-1, 2, 0)
x = point[0]
y = point[1]
z = point[2]
print(f'x={x}, y={y}, z={z}')
x=-1, y=2, z=0
A more convenient way is:
x, y, z = point
print(f'x={x}, y={y}, z={z}')
x=-1, y=2, z=0
Adding an element to the list:
a.append('new_element')
a
[5, 2, 3, 51000.0, 'new_element']
Another sequence type that is used a lot in computational work is the ndarray
type (n-dimensional array) from the numpy
package. We can create a numpy array from other sequences, such as a list:
import numpy as np # by convention `np` is used as the alias for numpy
c = np.array([5, 2, 10, 100])
c
array([ 5, 2, 10, 100])
type(c)
numpy.ndarray
The ndarray
data type has been designed for numeric work. It is fast in execution and allows to carry out the same operation on all elements of the array at the same time:
3*c
array([ 15, 6, 30, 300])
np.sqrt(c) # element-wise square root
array([ 2.23606798, 1.41421356, 3.16227766, 10. ])
c.sum()
np.int64(117)
The Ubermag modules, such as discretisedfield
, often return numpy arrays.
Dictionaries map keys (such as region1
) to values (such as 1e-12
):
d = {'region1': 1e-12, 'region797': 5e-11}
d
{'region1': 1e-12, 'region797': 5e-11}
Accessing an element in a dictionary
d['region1'] # string in quotes
1e-12
All lines belonging to one execution branch must be indented.
a = 5
b = 4
if a == 5 and b < 10:
# indented lines
print("I'm in!") # single and double quotes
a += 1 # a = a + 1
a # output the value
I'm in!
6
if a == 10:
print('A')
elif a <= 4:
print('B')
else:
print('C')
C
for i in [1, 2, 3, 5.1]:
print(i)
1 2 3 5.1
a = [0, 5, 9, 4]
for i in range(len(a)):
print(f'{a[i]} + 1 = {a[i] + 1}') # f-string
0 + 1 = 1 5 + 1 = 6 9 + 1 = 10 4 + 1 = 5
for i in a:
print(f'{i} + 1 = {i + 1}')
0 + 1 = 1 5 + 1 = 6 9 + 1 = 10 4 + 1 = 5
def area(a, b):
# indented
return a * b
area(5, 2)
10
def sum_of_elements(a):
s = 0
for i in a:
s = s + i
return s
sum_of_elements([1, 2, 3])
6
def volume(a, b, c):
return a * b * c
volume(1, 2, 3)
6
def volume(a, b=2, c=3):
return a * b * c
volume(1)
6
import
¶import numpy
numpy.pi
3.141592653589793
Often we specify an alias
import numpy as np
np.pi
3.141592653589793
def speed(s, t)
return s/t
Cell In[52], line 1 def speed(s, t) ^ SyntaxError: expected ':'
def speed(s, t):
return s/t
Cell In[53], line 2 return s/t ^ IndentationError: expected an indented block after function definition on line 1
a = 10
b = 'a'
a + b
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[54], line 3 1 a = 10 2 b = 'a' ----> 3 a + b TypeError: unsupported operand type(s) for +: 'int' and 'str'
my_var + 5
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[55], line 1 ----> 1 my_var + 5 NameError: name 'my_var' is not defined
import scipy
scpy.fft.fft() # typo: scpy instead of scipy
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[56], line 2 1 import scipy ----> 2 scpy.fft.fft() # typo: scpy instead of scipy NameError: name 'scpy' is not defined
In Python, everything is an object. Each object contains attributes and methods (functions). When we define an object, using .
we can access its different methods. For instance, if we define a string:
my_object = "Ubermag"
Now we can access some of its methods:
my_object.lower()
'ubermag'
We can see all methods and attributes of an object using the dir()
function:
In Jupyter notebooks, it is often enough to append a question mark to the function name:
import math
math.sqrt?
Signature: math.sqrt(x, /) Docstring: Return the square root of x. Type: builtin_function_or_method
Alternatively, use the help()
function to get more information about an object or method:
help(math.sqrt)
Help on built-in function sqrt in module math: sqrt(x, /) Return the square root of x.
A more detailed Introduction to Python for scientists and engineers is available
More generic documentation and tutorials can be found on the Python home page at https://www.python.org/