Python - Basics

Python

  • High−level.

  • Clean, readable, and efficient.

  • Easy and fun to learn.

  • Dynamic.

  • Fast to write and test code.

  • Less code.

  • Flexible.

  • Interactive.

  • Great support

  • Open source.

  • Vast range of libraries.

  • Huge number of users.

  • Slow (sometimes).

Data types

x = 10
type(x)
int
y = 0.5
type(y)
float
x + y
10.5
z = x / 2
z
5.0
type(z)
float
int(z)
5
my_string = 'Hello'
type(my_string)
str
print(my_string)
Hello
my_string.upper()
'HELLO'
greeting = 'Hello, I am Gary.'
greeting
'Hello, I am Gary.'
greeting.split(' ')
['Hello,', 'I', 'am', 'Gary.']
greeting.replace("Gary", "Gary's Mother")
"Hello, I am Gary's Mother."
'-'.join(greeting)
'H-e-l-l-o-,- -I- -a-m- -G-a-r-y-.'
my_list = [1, 2, 3, 4, 5]
type(my_list)
list
len(my_list)
5
my_list[0]
1
my_list[-1]
5
my_list[-1] = my_string
my_list
[1, 2, 3, 4, 'Hello']
my_list.append(x)
my_list
[1, 2, 3, 4, 'Hello', 10]
[num for num in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
my_dict = {'a': 1, 'b': 2, 'c': 3}
type(my_dict)
dict
my_dict.keys()
dict_keys(['a', 'b', 'c'])
my_dict.values()
dict_values([1, 2, 3])
my_dict['b']
2
my_dict.update({'d': greeting})
my_dict
{'a': 1, 'b': 2, 'c': 3, 'd': 'Hello, I am Gary.'}
my_boolean = True
type(my_boolean)
bool
my_boolean == True
True
my_boolean == False
False

Control flow

if 10 < 20:
    print(f'Truthy')
Truthy
if True:
    print(f'Truthy')
Truthy
for num in range(5):
    print(num)
0
1
2
3
4
for num in range(5):
    if num % 2 == 0:
        print(f'{num} is even')
0 is even
2 is even
4 is even
for num in range(5):
    if num % 2 == 0:
        print(f'{num} is even')
    else:
        print(f'{num} is odd')
0 is even
1 is odd
2 is even
3 is odd
4 is even
colours = ['red', 'green', 'blue']
for index, colour in enumerate(colours):
    print(index, colour)
0 red
1 green
2 blue
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(key, value)
a 1
b 2
c 3

Modules

import os
os.getcwd()
'/home/lukeconibear/introduction_to_scientific_computing/book'
import glob
glob.glob('*bash')
['dask_on_hpc.bash']
import re
re.findall(r'\d+', 'Hello 12345')
['12345']

Functions

def say_hello(*args): # arguments
    for arg in args:
        print(f'Hello {arg}!')
say_hello('Gary')
Hello Gary!
say_hello('Gary', "Gary's Mother")
Hello Gary!
Hello Gary's Mother!
def do_maths(x=2, y=3, z=4): # keyword arguments
    print(f'x = {x}')
    print(f'y = {y}')
    print(f'z = {z}')
    result = (x + y) * z
    print(f'result = {result}')
do_maths()
x = 2
y = 3
z = 4
result = 20
do_maths(1, 2, 3)
x = 1
y = 2
z = 3
result = 9
do_maths(3, 2, 1)
x = 3
y = 2
z = 1
result = 5
do_maths(z=3, y=2, x=1)
x = 1
y = 2
z = 3
result = 9
def do_maths(**kwargs): # keyword arguments
    print(kwargs)
    return sum(kwargs.values())
result = do_maths(x=2, y=3, z=4)
{'x': 2, 'y': 3, 'z': 4}
result
9

For more information, see the documentation.