def is_prime(x):
for j in range(2, x):
if x % j == 0:
return False
return True
is_prime(7)
With loop
def factorial(x):
fact = 1
for i in range(1,x+1):
fact = fact * i
return fact
Without loop
def factorial(x):
if x > 0:
return x * factorial(x - 1)
else:
return 1
def mean(x):
return sum(x) / float(len(x))
mean([1, 3, 4, 5, 6, 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])
jmag
for name in sorted(jmag): # alphabetical
print(name, jmag[name])
# 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()
%cat data_new.txt
import math
math.cos(math.radians(60))
math.sin(math.pi / 6)