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))
In [3]:
hydrometeors = ['rain', 'snow', 'hail'] # create a list holding three elements
print(hydrometeors)
print('length:', len(hydrometeors))
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)
In [5]:
hydrometeors = ['rain', 'snow', 'hail']
hydrometeors.append('drizzle') # add 'drizzle' to the end of the list
print(hydrometeors)
In [6]:
hydrometeors = ['rain', 'snow', 'hail']
hydrometeors.insert(1, 'graupel') # insert graupel before position 1
print(hydrometeors)
In [7]:
hydrometeors = ['rain', 'snow', 'hail']
del hydrometeors[0] # remove the first element from the list
print(hydrometeors)
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)
In [9]:
hydrometeors = ['rain', 'snow', 'hail']
print("Before change:", hydrometeors)
hydrometeors[0] = 'virga'
print("After change:", hydrometeors)
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])
In [11]:
hydrometeors[3] # Trying to access elements which do not exist raises a IndexError
In [12]:
hydrometeors = ['rain', 'snow', 'hail']
print('index -1:', hydrometeors[-1])
print('index -2:', hydrometeors[-2])
print('index -3:', hydrometeors[-3])
In [13]:
hydrometeors = ['rain', 'snow', 'hail', 'drizzle', 'graupel', 'virga']
print(hydrometeors[2:4]) # select elements from index 2 to index 4
In [14]:
hydrometeors[:3] # start from beginning
Out[14]:
In [15]:
hydrometeors[3:] # until the end
Out[15]:
In [16]:
hydrometeors[3:-1] # negative indices
Out[16]:
In [17]:
hydrometeors[1::2] # every 2nd element
Out[17]:
In [18]:
t = ('rain', 'snow', 'hail')
print(t)
print(len(t))
In [19]:
t[0] = 'virga' # tuples cannot be changed
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)
In [21]:
d = {'site': 'KLOT', 'amount': 20, 'wind': 'east'}
In [22]:
print(d.keys())
In [23]:
print(d.values())
In [24]:
print('site:', d['wind'])
print('amount:', d['amount'])
print('wind:', d['wind'])
In [25]:
print("wind before change:", d['wind'])
d['wind'] = 'west'
print("wind after change:", d['wind'])
Entries can be added or remove from dictionaries
In [26]:
d = {'site': 'KLOT', 'amount': 20, 'wind': 'east'}
print(d)
In [27]:
del d['wind']
print(d)
In [28]:
d['wind_speed'] = 'east'
d['wind_direction'] = '10 m/s'
print(d)
Note: Dictionaries do not preserve the order in which entries are added. If you need ordering use a OrderedDict from the collections module.
In [29]:
hydrometeor = 'rain'
if hydrometeor == 'rain':
print("You saw rain")
In [30]:
hydrometeor = 'hail'
if hydrometeor == 'rain':
print("You saw rain")
else:
print("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")
In [32]:
hydrometeors = ['rain', 'snow', 'hail']
for hydrometeor in hydrometeors: # loop over elements in a list
print(hydrometeor)
In [33]:
for i in range(5): # loop over the number 0 to 4
print(i)
In [34]:
d = {'site': 'KLOT', 'amount': 20, 'wind': 'east'}
for key, value in d.items():
print(key, ':', value)
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)
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))
In [39]:
say_hello()
In [40]:
favorite_hydrometeor("Jonathan")
In [41]:
favorite_hydrometeor("Jonathan", hydrometeor="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)
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)
In [46]:
home.sum_of_coordinates()
Out[46]:
In [47]:
import math # import the entire math module
In [48]:
math.sqrt(2)
Out[48]:
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))