Tutorial: Python Programming 101

Functions

The Python language also allows you to create your own functions. Functions are like miniature programs within your script. They come in handy when you're going to do the same thing repeatedly because you can just call that function anytime you want it.

 

For example, let's create a function that multiplies variables by 3. This function will let us drop any variable we want into it and it will return the answer. Write the following lines into your script.

 

 

#These first lines define a new function named newlitter.
#This function accepts one #variable which will be called 'animal'
#within the body of the function.
def newlitter(animal):
  #Multiply the given variable by three.
  newnumber = animal*3
  #Return a value.
  return newnumber

#Call the function and put the variable "pigs" into it.
# The variable "new_pigs" will be equal to the value that was returned from the function.
new_pigs = newlitter(pigs)

#Call the function again, but this time put the variable cows into it.
new_cows = newlitter(cows)

#Print the products of the function.
print "The new number of pigs is", new_pigs
print "The new number of cows is", new_cows

 

 

Once a function has been written into a script, you can call it anytime you want to use it.

 

 

 

 

 

Speaking Vizard's language

A quick note: Tips on scripts

Looping logic

If-then logic

Functions

An example

More about Python