<jupyter_start><jupyter_text>Python basicsThe purpose of this tutorial is to introduce some basic Python syntax, which can help understand ubermag simulations. VariablesPython is a dynamic language. That means that no type is associated to the variable at the definition and can be changed at any point by assigning a value of different type.<jupyter_code>a = 10
type(a)
a = 3.14  # decimal point present
type(a)
a = 'Python'
type(a)
a = (1, 2, 3)  # tuple: round brackets
type(a)
a = ['a', 2, 3.14]  # list: square brackets
type(a)<jupyter_output><empty_output><jupyter_text>Large/small values, e.g. $a = 2.1 \times 10^{6}$<jupyter_code>a = 2.1e-6
a<jupyter_output><empty_output><jupyter_text>Basic operations 1. Addition $c = a + b$<jupyter_code>a = 10
b = 3
c = a + b<jupyter_output><empty_output><jupyter_text>To output the value:<jupyter_code>c  # outputs the variable value<jupyter_output><empty_output><jupyter_text>Similarly, `print()` function can be used.<jupyter_code>print('The value of c is:', c)<jupyter_output>The value of c is: 13<jupyter_text>2. Subtraction: $a - b$<jupyter_code>a - b<jupyter_output><empty_output><jupyter_text>3. Multiplication: $a \times b$<jupyter_code>a * b<jupyter_output><empty_output><jupyter_text>4. Division: $a / b$<jupyter_code>a / b<jupyter_output><empty_output><jupyter_text>In Python 3, if we divide two `int` variables, we are going to get `float`;<jupyter_code>5/2<jupyter_output><empty_output><jupyter_text>5. Power $a^{b}$<jupyter_code>a = 5
b = 3
a ** b  # Common mistake to write a^b<jupyter_output><empty_output><jupyter_text>6. More complicated operationsOther "more complicated" operations generally live in `math` or `numpy`. Before `math` can be used, it must be imported.<jupyter_code>import math<jupyter_output><empty_output><jupyter_text>All functions living in `math` or any other module, can be accessed using `.` operator.<jupyter_code>theta = 3.14159  # theta = pi
math.sin(theta)
math.cos(theta)
math.sin(math.pi/2)
a = 10
math.log10(a)
math.log(math.e)  # natural log<jupyter_output><empty_output><jupyter_text>Lists and tuplesA collection of values can be represented using lists and tuples.<jupyter_code>a = [1, 2, 3, 5.1e4]  # list -> square bracket
a
b = (1, 2, 3, 5.1e4)  # tuple -> round bracket
b<jupyter_output><empty_output><jupyter_text>Indexing<jupyter_code>a[0]  # the first element
a[0] = 5
a
b[3]  # the last element<jupyter_output><empty_output><jupyter_text>Alternatively $-1$ can be used as an index to get the last element<jupyter_code>a[-1]<jupyter_output><empty_output><jupyter_text>Length (the number of elements)<jupyter_code>len(a)
len(b)<jupyter_output><empty_output><jupyter_text>What is the difference between list and tuple? Tuples are not mutable.<jupyter_code>b[2] = 3<jupyter_output><empty_output><jupyter_text>UnpackingIf we have a point which is defined as a tuple and want to unpack the values into x, y, and z, we can write:<jupyter_code>point = (-1, 2, 0)
x = point[0]
y = point[1]
z = point[2]
print(f'x={x}, y={y}, z={z}')<jupyter_output>x=-1, y=2, z=0<jupyter_text>A more convenient way is:<jupyter_code>x, y, z = point
print(f'x={x}, y={y}, z={z}')<jupyter_output>x=-1, y=2, z=0<jupyter_text>Adding an element to the list:<jupyter_code>a.append('new_element')
a<jupyter_output><empty_output><jupyter_text>Dictionaries<jupyter_code>d = {'region1': 1e-12, 'region797': 5e-11}
d<jupyter_output><empty_output><jupyter_text>Indexing<jupyter_code>d['region1']  # string in quotes<jupyter_output><empty_output><jupyter_text>SelectionAll lines belonging to a certain branch must be indented.<jupyter_code>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
if a == 10:
    print('A')
elif a <= 4:
    print('B')
else:
    print('C')<jupyter_output>C<jupyter_text>Iteration<jupyter_code>for i in [1, 2, 3, 5.1]:
    print(i)
a = [0, 5, 9, 4]
for i in range(len(a)):
    print(f'{a[i]} + 1 = {a[i] + 1}')  # f-string
for i in a:
    print(f'{i} + 1 = {i + 1}')<jupyter_output>0 + 1 = 1
5 + 1 = 6
9 + 1 = 10
4 + 1 = 5<jupyter_text>Functions<jupyter_code>def area(a, b):
    # indented
    return a*b  # return should not be confused with print!

area(5, 2)
def sum_of_elements(a):
    s = 0
    for i in a:
        s += i
        
    return s

sum_of_elements([1, 2, 3])<jupyter_output><empty_output><jupyter_text>Keyword arguments<jupyter_code>def volume(a, b, c):
    return a * b * c

volume(1, 2, 3)
def volume(a, b=2, c=3):
    return a * b * c

volume(1)<jupyter_output><empty_output><jupyter_text>Imports<jupyter_code>import numpy

numpy.pi<jupyter_output><empty_output><jupyter_text>Often we specify an alias<jupyter_code>import numpy as np

np.pi  # alias is used<jupyter_output><empty_output><jupyter_text>Common mistakes 1. No colon<jupyter_code>def speed(s, t)
    return s/t<jupyter_output><empty_output><jupyter_text>2. No indentation<jupyter_code>def speed(s, t):
return s/t<jupyter_output><empty_output><jupyter_text>3. Mixing types<jupyter_code>a = 10
b = 'a'
a + b<jupyter_output><empty_output><jupyter_text>4. Using an undefined variable<jupyter_code>my_var + 5<jupyter_output><empty_output><jupyter_text>5. Module is not imported<jupyter_code>import scipy as scp  # typo
scpy.fft.fft()<jupyter_output><empty_output><jupyter_text>Object oriented programming basicsIn 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:<jupyter_code>my_object = "Ubermag"<jupyter_output><empty_output><jupyter_text>Now we can access some of its methods:<jupyter_code>my_object.lower()<jupyter_output><empty_output><jupyter_text>Getting helpIn Jupyter notebook, it is often enough to append a question mark to the function name.<jupyter_code>import numpy as np
np.mean?<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12907563025210084, 'fraction_numerical': 0.02453781512605042, 'mean_word_length': 5.879768786127167, 'pattern_counts': {'":': 0, '<': 142, '<?xml version=': 0, '>': 142, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '36', 'dir': 'jupyter-structured-clean-dedup', 'id': '436347', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 2443, 'n_tokens_neox': 2327, 'n_words': 582, 'path': 'getting-started/python-basics.ipynb', 'repo_name': 'ubermag/tutorials', 'size': '5950'}