Python

  • High-level
  • General purpose
  • Multiple programming paradigms
  • Interpreted

Variables


In [1]:
var1 = 1              # interger
var2 = 2.34           # floating point numbers
var3 = 5.6 + 7.8j     # complex numbers 
var4 = "Hello World"  # strings
var5 = True           # booleans
var6 = None           # special value to indicate the absence of a value

In [2]:
print("var1 value:", var1, "type:", type(var1))
print("var2 value:", var2, "type:", type(var2))
print("var3 value:", var3, "type:", type(var3))
print("var4 value:", var4, "type:", type(var4))
print("var5 value:", var5, "type:", type(var5))
print("var6 value:", var6, "type:", type(var6))


var1 value: 1 type: <class 'int'>
var2 value: 2.34 type: <class 'float'>
var3 value: (5.6+7.8j) type: <class 'complex'>
var4 value: Hello World type: <class 'str'>
var5 value: True type: <class 'bool'>
var6 value: None type: <class 'NoneType'>

Containers

Data types for holding many variables

Lists

One-dimensional, ordered container whose contents and length can change (mutable).


In [3]:
hydrometeors = ['rain', 'snow', 'hail']  # create a list holding three elements
print(hydrometeors)
print('length:', len(hydrometeors))


['rain', 'snow', 'hail']
length: 3

The elements of a list do not need to be of the same type:


In [4]:
mixed_type_list = ['rain', 4.5, 99, None]
print(mixed_type_list)


['rain', 4.5, 99, None]

Elements can be added or removed from a list


In [5]:
hydrometeors = ['rain', 'snow', 'hail']
hydrometeors.append('drizzle')  # add 'drizzle' to the end of the list
print(hydrometeors)


['rain', 'snow', 'hail', 'drizzle']

In [6]:
hydrometeors = ['rain', 'snow', 'hail']
hydrometeors.insert(1, 'graupel')  # insert graupel before position 1
print(hydrometeors)


['rain', 'graupel', 'snow', 'hail']

In [7]:
hydrometeors = ['rain', 'snow', 'hail']
del hydrometeors[0]  # remove the first element from the list
print(hydrometeors)


['snow', 'hail']

In [8]:
hydrometeors = ['rain', 'snow', 'hail']
observation = hydrometeors.pop()  # remove the last item from the list and store it in hydrometeor
print("observation:", observation)
print("hydrometeors:", hydrometeors)


observation: hail
hydrometeors: ['rain', 'snow']

Elements of a list can be changed


In [9]:
hydrometeors = ['rain', 'snow', 'hail']
print("Before change:", hydrometeors)
hydrometeors[0] = 'virga'
print("After change:", hydrometeors)


Before change: ['rain', 'snow', 'hail']
After change: ['virga', 'snow', 'hail']

Lists Indexing


In [10]:
hydrometeors = ['rain', 'snow', 'hail']
print('index 0:', hydrometeors[0])   # indexing begins at 0
print('index 1:', hydrometeors[1])
print('index 2:', hydrometeors[2])


index 0: rain
index 1: snow
index 2: hail

In [11]:
hydrometeors[3]  # Trying to access elements which do not exist raises a IndexError


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-11-7706668d582b> in <module>()
----> 1 hydrometeors[3]  # Trying to access elements which do not exist raises a IndexError

IndexError: list index out of range

In [12]:
hydrometeors = ['rain', 'snow', 'hail']
print('index -1:', hydrometeors[-1])
print('index -2:', hydrometeors[-2])
print('index -3:', hydrometeors[-3])


index -1: hail
index -2: snow
index -3: rain

List slicing

Syntax: list_variable[start:end:step]


In [13]:
hydrometeors = ['rain', 'snow', 'hail', 'drizzle', 'graupel', 'virga']
print(hydrometeors[2:4])  # select elements from index 2 to index 4


['hail', 'drizzle']

In [14]:
hydrometeors[:3]  # start from beginning


Out[14]:
['rain', 'snow', 'hail']

In [15]:
hydrometeors[3:]  # until the end


Out[15]:
['drizzle', 'graupel', 'virga']

In [16]:
hydrometeors[3:-1]  # negative indices


Out[16]:
['drizzle', 'graupel']

In [17]:
hydrometeors[1::2]  # every 2nd element


Out[17]:
['snow', 'drizzle', 'virga']

Tuples

One-dimensional, ordered container whose contents and length CANNOT change (immutable).


In [18]:
t = ('rain', 'snow', 'hail')
print(t)
print(len(t))


('rain', 'snow', 'hail')
3

In [19]:
t[0] = 'virga'  # tuples cannot be changed


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-d4fc2c3241e8> in <module>()
----> 1 t[0] = 'virga'  # tuples cannot be changed

TypeError: 'tuple' object does not support item assignment

Can be 'unpacked' to assign variable. Often used with functions which return multiple items.


In [20]:
observations = ('rain', 'snow', 'hail')  # tuple with three elements
obs1, obs2, obs3 = observations    # unpack tuple into obs1, obs2, obs3 variables
print("observations:", observations)
print("obs1:", obs1)
print("obs2:", obs2)
print("obs3:", obs3)


observations: ('rain', 'snow', 'hail')
obs1: rain
obs2: snow
obs3: hail

Dictionaries

Unordered collection of key/value pairs whose size and content can change


In [21]:
d = {'site': 'KLOT', 'amount': 20, 'wind': 'east'}

In [22]:
print(d.keys())


dict_keys(['wind', 'site', 'amount'])

In [23]:
print(d.values())


dict_values(['east', 'KLOT', 20])

In [24]:
print('site:', d['wind'])
print('amount:', d['amount'])
print('wind:', d['wind'])


site: east
amount: 20
wind: east

In [25]:
print("wind before change:", d['wind'])
d['wind'] = 'west'
print("wind after change:", d['wind'])


wind before change: east
wind after change: west

Entries can be added or remove from dictionaries


In [26]:
d = {'site': 'KLOT', 'amount': 20, 'wind': 'east'} 
print(d)


{'wind': 'east', 'site': 'KLOT', 'amount': 20}

In [27]:
del d['wind']
print(d)


{'site': 'KLOT', 'amount': 20}

In [28]:
d['wind_speed']  = 'east'
d['wind_direction'] = '10 m/s'
print(d)


{'wind_speed': 'east', 'wind_direction': '10 m/s', 'site': 'KLOT', 'amount': 20}

Note: Dictionaries do not preserve the order in which entries are added. If you need ordering use a OrderedDict from the collections module.

Flow control

If statements


In [29]:
hydrometeor = 'rain'
if hydrometeor == 'rain':
    print("You saw rain")


You saw rain

In [30]:
hydrometeor = 'hail'
if hydrometeor == 'rain':
    print("You saw rain")
else:
    print("You did NOT see rain")


You did NOT see rain

In [31]:
hydrometeor = 'snow'
if hydrometeor == 'rain':
    print("You saw rain")
elif hydrometeor == 'snow':
    print("You saw snow")
else:
    print("I do not know what you saw")


You saw snow

for loops

Syntax:
for variable in iterable:
    code block


In [32]:
hydrometeors = ['rain', 'snow', 'hail']
for hydrometeor in hydrometeors:  # loop over elements in a list
    print(hydrometeor)


rain
snow
hail

In [33]:
for i in range(5):  # loop over the number 0 to 4
    print(i)


0
1
2
3
4

In [34]:
d = {'site': 'KLOT', 'amount': 20, 'wind': 'east'} 
for key, value in d.items():
    print(key, ':', value)


wind : east
site : KLOT
amount : 20

Functions


In [35]:
# simple
def func(arg1):
    print(arg1)
    return 42

In [36]:
# call a function
return_value = func("Hello World")
print("ret_value:", return_value)


Hello World
ret_value: 42

Functions can have multiple, no and even default arguments


In [37]:
def add_numbers(number1, number2):
    return number1 + number2

def say_hello():
    print("Hello AMS")
    
def favorite_hydrometeor(name, hydrometeor='snow'):
    print("Hello", name)
    print("Your favorite hydrometeor is", hydrometeor)

In [38]:
print(add_numbers(1, 2))


3

In [39]:
say_hello()


Hello AMS

In [40]:
favorite_hydrometeor("Jonathan")


Hello Jonathan
Your favorite hydrometeor is snow

In [41]:
favorite_hydrometeor("Jonathan", hydrometeor="hail")


Hello Jonathan
Your favorite hydrometeor is hail

Functions can return multiple values:


In [42]:
def sum_and_product(a, b):
    return a+b, a*b
sum_ab, product_ab = sum_and_product(2, 3)
print("sum", sum_ab)
print("product", product_ab)


sum 5
product 6

Classes


In [43]:
class Point(object):
    """ A class to store the coordinate in a plane"""
    
    def __init__(self, x, y):
        self.x = x   # an attribute
        self.y = y   # an attribute
        
    def sum_of_coordinates(self):  # a class method
        return self.x + self.y

In [44]:
home = Point(2, 3)

In [45]:
print(home.x)
print(home.y)


2
3

In [46]:
home.sum_of_coordinates()


Out[46]:
5

Libraries

  • Python has a large number of libraries which extend the basic functionality.
  • The standard library is included with Python and contains a number of helpful features.
  • Third-party libraries can add even more powerful functionality!
  • Libraries must be imported to be used.

In [47]:
import math  # import the entire math module

In [48]:
math.sqrt(2)


Out[48]:
1.4142135623730951

In [49]:
from random import randrange   # import just the randrange function from the random module

In [50]:
for i in range(5):
    print(randrange(1, 10))


3
3
8
3
5