07. Functions

Exercise 1

In [1]:
def is_prime(x):
    for j in range(2, x):
        if x % j == 0:
            return False
    return True
In [2]:
is_prime(7)
Out[2]:
True

Exercise 2

With loop

In [3]:
def factorial(x):
    fact = 1
    for i in range(1,x+1):
        fact = fact * i
    return fact

Without loop

In [4]:
def factorial(x):
    if x > 0:
        return x * factorial(x - 1)
    else:
        return 1

Exercise 3

In [5]:
def mean(x):
    return sum(x) / float(len(x))
In [6]:
mean([1, 3, 4, 5, 6, 7])
Out[6]:
4.333333333333333

08. Reading and writing files

Exercise 1

In [7]:
# Open file
f = open('data/data.txt', 'r')

# Read and ignore header lines
header1 = f.readline()
header2 = f.readline()
header3 = f.readline()

jmag = {}
for line in f:
    line = line.strip()
    columns = line.split()
    name = columns[2]
    jmag[name] = float(columns[3])
In [8]:
jmag
Out[8]:
{'00424403+4116069': 9.321,
 '00424403+4116108': 11.507,
 '00424433+4116085': 9.453,
 '00424446+4116016': 12.07,
 '00424455+4116103': 10.773,
 '00424464+4116092': 9.299,
 '00424464+4116106': 9.399}
In [9]:
for name in sorted(jmag):  # alphabetical
    print(name, jmag[name])
00424403+4116069 9.321
00424403+4116108 11.507
00424433+4116085 9.453
00424446+4116016 12.07
00424455+4116103 10.773
00424464+4116092 9.299
00424464+4116106 9.399

Exercise 2

In [10]:
# Open file
f_in = open('data/data.txt', 'r')
f_out = open('data_new.txt', 'w')

# Read and ignore header lines
header1 = f_in.readline()
header2 = f_in.readline()
header3 = f_in.readline()

# Loop over lines and extract variables of interest
for line in f_in:
    line = line.strip()
    columns = line.split()
    name = columns[2]
    jmag = float(columns[3])
    f_out.write(name + " " + str(jmag) + "\n")

f_out.close()
In [11]:
%cat data_new.txt
00424433+4116085 9.453
00424403+4116069 9.321
00424455+4116103 10.773
00424464+4116092 9.299
00424403+4116108 11.507
00424464+4116106 9.399
00424446+4116016 12.07

09. Modules and Variable Scope

In [12]:
import math
In [13]:
math.cos(math.radians(60))
Out[13]:
0.5000000000000001
In [14]:
math.sin(math.pi / 6)
Out[14]:
0.49999999999999994