(see https://docs.python.org/2/tutorial/controlflow.html#defining-functions)
Functions increase the modularity and functionality of your code. Create functions for pieces of code that you will use more than once. That makes your code easier to read.
In [1]:
def area_circle(radius, pi=3.14):
"""determine area of a circle, given its radius""" # documentation!
return pi*radius*radius
print area_circle(3) # uses the default value of 'pi'
print area_circle(3, pi=3) # uses your own value of 'pi'
print area_circle.__doc__
Note that code that is part of a function has to be indented. return
literally returns some value that replaces the function call - in this case, it acts as an argument to print
. A documentation line briefly describing what the function does is a sign of good manners and useful to other people using your code.
A special case of function is a lambda
function. It allows for defining so-called "inline" functions in your code:
In [2]:
area = lambda r: 3.14*r*r
area(3)
Out[2]:
Python supports "functional programming", which means that functions can be passed as arguments to other functions:
In [3]:
print map(lambda x: x+3, range(10))
(see https://docs.python.org/2/tutorial/modules.html)
Modules provide additional functionality. Importing modules allows you to access functions, variables, and other things defined within their "namespace". The namespace concept is important to understand how to use modules properly.
In [4]:
a = 3
print dir()
dir()
prints all elements in the current namespace of your program (e.g., variable a
). Your namespace contains all functions, variables, etc. that you have created as part of your code.
Let's come back to modules. There are different ways to import modules that have different effects on your namespace. This is the easiest way:
In [5]:
import math
dir(math)
Out[5]:
In order to address any element in the math
namespace, you have to specifically tell Python that this element is in the math
namespace:
In [6]:
#sqrt(4) # will cause a NameError, as sqrt is not defined in your namespace
print math.sqrt(4)
You can rename namespaces of modules upon importing them:
In [7]:
import math as m
print m.sqrt(9)
Or you can import the entire namespace of a module in your namespace:
In [8]:
from math import *
print sqrt(16)
However, this is dangerous, as you might up with a namespace where different things share the same name. Try not to use from XXX import *
. Instead, you can import specific things of which you know that you will use them more often:
In [9]:
from math import sqrt
print sqrt(36)
This is just a quick introduction of some libraries that you might want to use regularly in the future. See https://docs.python.org/2/library/index.html#library-index for more details.
In [10]:
import math
print math.pi
print math.sqrt(4) # square root
print math.fabs(-3.13) # absolute value (for floats)
print math.exp(1) # exponential function
print math.log(math.e) # natural log
print math.log10(100) # base-10 log
print math.cos(0) # cosine
print math.sin(math.pi) # sine
In [11]:
import os
print os.getcwd() # get the current working directory
os.chdir('../') # change the current working directory
print os.listdir('.') # list files and directories in this directory
os.mkdir('/tmp/test') # create directory
os.rmdir('/tmp/test') # remove directory
os.access('test.dat', os.F_OK) # check if file exists
os.remove('test.dat') if os.access('test.dat', os.F_OK) else None # remove a file if it exists
#os.abort() # abort code execution
A powerful script that walks from a specific directory downwards:
In [ ]:
for root, dirs, files in os.walk('.'):
print 'in', root
print ' files', files
In [13]:
import datetime
a = datetime.datetime.now() # current time (local time)
b = datetime.datetime.utcnow() # current time (UT)
print a + datetime.timedelta(minutes=30) # add 30 minutes to datetime object
a_str = a.strftime("%d/%m/%y %H:%M:%S") # nicely format datetime object
print datetime.datetime.strptime(a_str, "%d/%m/%y %H:%M:%S") # convert string to datetime object
In [14]:
import time
start = time.time()
# do stuff
print time.time()-start # number of seconds it took the code to run
In [15]:
import urllib2
url = 'http://nearearthobjects.nau.edu/neosurvey/results.html'
a = urllib2.urlopen(url).readlines() # grab website source code
#print a
In [16]:
import subprocess
subprocess.Popen(['ls', '-1']) # call 'ls -1'
s = subprocess.Popen(['ls', '-1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # call 'ls -1' and catch the screen output
s.wait() # wait for s to end
output = s.communicate()[0].split('\n')
print output