Skip to main content

function_examples.py


# do nothing:
def nothing ():
    """Do Nothing"""
    pass
nothing()
# print message
def message():
    """Print a message"""
    print 'This is a message to you.'
message()
###########
def vol_sphere(radius):
    """Calculate volume of a sphere
    Argument:
        radius: radius of the sphere
    Returns:
        Volume of the sphere as a float
    """
    pi=3.14	# local variable
    return 4./3.*pi*(radius**3)
#now use the function
r=2.5 #cm
V=vol_sphere(r) #cm3
print 'Volume=',V
###########
def read_data_2col(filename):
    """Read data file with two columns of floats
    Args:
        filename: a string indicating the file name
    Returns:
    """
    f=open(filename,'r')
    #initialise list
    L1=[]
    L2=[]
    #fill the list
    for line in f:
        x,y=line.split()
        L1.append(float(x))
        L2.append(float(y))
    return L1,L2
t,x=read_data_2col('data_2col.txt')
print t
print x
###
# return values
def three_ints():
    i=1
    j=2
    k=3
    return (i,j,k)
# function call
i,j,k=three_ints()
def coord_leeds():
    lat=53.8
    lon=1.5
    return {'lat':lat,'lon':lon}
# function call
coord=coord_leeds()
print 'latitude of Leeds:',coord['lat']