#!/usr/bin/env python # coding: utf-8 # # Python basics # # The purpose of this tutorial is to introduce some basic Python syntax, which can help understand Ubermag simulations. # # ## Variables # 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: # In[1]: a = 10 type(a) # In[2]: a = 3.14 # decimal point present makes this a float type type(a) # In[3]: a = 'Python' # single or double quotes define a string type(a) # In[4]: a = (1, 2, 3) # tuple: round brackets type(a) # In[5]: a = ['a', 2, 3.14] # list: square brackets type(a) # Large/small values, e.g. $a = 2.1 \times 10^{6}$ # In[6]: a = 2.1e-6 a # ## Basic arithmetic operations # # #### 1. Addition $c = a + b$ # In[7]: 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: # In[8]: c # The `print()` function can be used to send information to the standard output (typically the display): # In[9]: print('The value of c is:', c) # #### 2. Subtraction: $a - b$ # In[10]: a - b # #### 3. Multiplication: $a \times b$ # In[11]: a * b # #### 4. Division: $a / b$ # In[12]: a / b # In Python 3, if we divide two `int` variables, we are going to get `float`: # In[13]: 5/2 # #### 5. Power $a^{b}$ # In[14]: a = 5 b = 3 a ** b # Common mistake to write a^b # #### 6. More complicated operations # # Other "more complicated" operations generally live in `math` or `numpy`. Before `math` can be used, it must be imported. # In[15]: import math # All functions living in `math` or any other module, can be accessed using `.` operator. # In[16]: theta = 3.14159 # theta is approximately pi math.sin(theta) # In[17]: math.cos(theta) # In[18]: math.sin(math.pi/2) # In[19]: a = 10 math.log10(a) # In[20]: math.log(math.e) # natural log # ## Sequences: lists and tuples # # A collection of values can be represented using lists and tuples. # In[21]: a = [1, 2, 3, 5.1e4] # list -> square bracket a # In[22]: b = (1, 2, 3, 5.1e4) # tuple -> round bracket b # #### Indexing # In[23]: a[0] # the first element # In[24]: a[0] = 5 a # In[25]: b[3] # the last element # Alternatively `-1` can be used as an index to get the last element # In[26]: a[-1] # #### Length (the number of elements in a sequence) # In[27]: len(a) # In[28]: len(b) # What is the difference between list and tuple? Tuples are not mutable. # In[29]: b[2] = 3 # #### Unpacking # # 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: # In[30]: point = (-1, 2, 0) x = point[0] y = point[1] z = point[2] print(f'x={x}, y={y}, z={z}') # A more convenient way is: # In[31]: x, y, z = point print(f'x={x}, y={y}, z={z}') # Adding an element to the list: # In[32]: a.append('new_element') a # ## Sequences: numpy arrays # # 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: # In[33]: import numpy as np # by convention `np` is used as the alias for numpy # In[34]: c = np.array([5, 2, 10, 100]) c # In[35]: type(c) # 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: # In[36]: 3*c # In[37]: np.sqrt(c) # element-wise square root # In[38]: c.sum() # The Ubermag modules, such as `discretisedfield`, often return numpy arrays. # ## Dictionaries # # Dictionaries map keys (such as `region1`) to values (such as `1e-12`): # In[39]: d = {'region1': 1e-12, 'region797': 5e-11} d # Accessing an element in a dictionary # In[40]: d['region1'] # string in quotes # ## Conditional execution # # All lines belonging to one execution branch must be indented. # In[41]: 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 # In[42]: if a == 10: print('A') elif a <= 4: print('B') else: print('C') # ## Iteration # In[43]: for i in [1, 2, 3, 5.1]: print(i) # In[44]: a = [0, 5, 9, 4] for i in range(len(a)): print(f'{a[i]} + 1 = {a[i] + 1}') # f-string # In[45]: for i in a: print(f'{i} + 1 = {i + 1}') # ## Functions # In[46]: def area(a, b): # indented return a * b area(5, 2) # In[47]: def sum_of_elements(a): s = 0 for i in a: s = s + i return s sum_of_elements([1, 2, 3]) # #### Default values for arguments # In[48]: def volume(a, b, c): return a * b * c volume(1, 2, 3) # In[49]: def volume(a, b=2, c=3): return a * b * c volume(1) # ## Accessing modules through `import` # In[50]: import numpy numpy.pi # Often we specify an alias # In[51]: import numpy as np np.pi # ## Common mistakes # # #### 1. No colon # In[52]: def speed(s, t) return s/t # #### 2. Lack of indentation # In[53]: def speed(s, t): return s/t # #### 3. Mixing incompatible types # In[54]: a = 10 b = 'a' a + b # #### 4. Using an undefined variable # In[55]: my_var + 5 # #### 5. Module is not imported # In[56]: import scipy scpy.fft.fft() # typo: scpy instead of scipy # ## Object oriented programming basics # # 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: # In[57]: my_object = "Ubermag" # Now we can access some of its methods: # In[58]: my_object.lower() # We can see all methods and attributes of an object using the `dir()` function: # ## Getting help # # In Jupyter notebooks, it is often enough to append a question mark to the function name: # In[59]: import math get_ipython().run_line_magic('pinfo', 'math.sqrt') # Alternatively, use the `help()` function to get more information about an object or method: # In[60]: help(math.sqrt) # ## Further reading # # - A more detailed [Introduction to Python for scientists and engineers is available](https://github.com/fangohr/introduction-to-python-for-computational-science-and-engineering/blob/master/Readme.md) # # - More generic documentation and tutorials can be found on the Python home page at https://www.python.org/