Python Tutorial Part VI: Functions 3
Auto Beauty Business Culture Dieting DIY Events Fashion Finance Food Freelancing Gardening Health Hobbies Home Internet Jobs Law Local Media Men's Health Mobile Nutrition Parenting Pets Pregnancy Products Psychology Real Estate Relationships Science Seniors Sports Technology Travel Wellness Women's Health

Python Tutorial Part VI: Functions 3

Part six of a Python tutorial for absolute beginners.

We learned about return values for functions in part V. In this installment, we're going to learn about arguments to functions.

An argument is a piece of data input to a subroutine, a subroutine being a section of code which a program can execute over and over again to do a specific task. By inputting an argument to a function, we can allow the function to return a value based on the input. Let's define a function with an argument to see this in action.

def addthree(x):

    x += 3

    print x

Call the function in the console by typing "addthree(5)" without quotes. The IDLE interpreter should print 8. So, what's going on here? Let's break it down and see what each line of code does.

The "def" is short for "define", which tells Python that we are defining a function. Some languages distinguish between declaring a function and defining it, but higher level languages like Python often do not. "addthree", when typed after "def", tells Python that the name of the function is "addthree", so we can call it by typing that name whenever we wish. The difference between this function and the ones we've written previously is that rather than being followed by a set of empty parentheses "()", it is followed by parentheses which enclose an x. This tells Python that our function will expect at least one argument. Calling the function without an argument by typing "addthree()" will raise a TypeError.

The argument acts in much the same way as a variable does (see article II in this series for an explanation of variables in Python). The first line of the function, "x += 3", tells Python to take whatever integer is stored in memory and adds 3 to it. When the interpreter reads, "print x", it takes that value and displays it on the screen.

Of course, integers aren't the only values which can be used as arguments to a function. Arguments can be strings, variables, and any number of other data types. 

To allow us to create more useful functions, we'll introduce a new data type and a new control tool.

def getintegers(x):

integers = []

while x<100:

x+=1

integers.append(x)

print integers

If you call the function with 10 as an argument by typing “getintegers(10)”, the interpreter will print a list of all values between 10 and 100. Let's take a look at the unfamiliar parts of the code to understand what's going on.

When we write “integers = []”, we are declaring an object called “integers” whose data type is list. A list is exactly what it sounds like: an object that stores objects and collects them as a list. If a variable is like a box that we can keep values in, then a list is like a row of boxes, each of which can contain its own values. You can have a list of integers, or a list of strings, or even a list of lists. I could, for example, declare a list containing all integers between 1 and 100, and call it A, then another list of strings containing the names of those variables (“one”, “two”, and so on) and call it B. I could then create a third list, C, which contains A and B.

The “while” statement is of particular interest to us because it saves us from writing a thousand “if” statements just to do the same thing over and over again. Essentially, Python executes the code inside of the “while” statement (in this case, all of the code behind the extra indent – some languages use curly brackets “{}”), checks to see if the condition is still true, then executes it again until the condition is met. Always be sure to build in a condition that ensures that the “while” loop will terminate – otherwise, it will continue into infinite until Python raises an error.

Notice that the “print” command at the end of the function is only executed once. This is because it only has one indent in front of it. The set of commands that Python will execute under the “while” conditions is delineated by the indentations: again, this is unique to Python. Other languages uses curly brackets for the most part.

Now for some exercises.

Try re-writing our second function with two arguments. Instead of executing as long as x is less than one hundred, allow it to execute as long as x is less than the second argument.

If you call “getintegers” using a number greater than 100 as an argument, it prints an empty list. Write the function so that it raises an error if the user attempts to input a number greater than 100. Hint: your solution should probably involve an “if” statement.

Computer image from publicdomainpictures.net

Looking for programming tools? Save when shopping online by using the latet programming tools coupons and pay less at popular retailers and brands. Find deals for popular programming tools stores using community-sourced coupons and deals.
Need an answer?
Get insightful answers from community-recommended
experts
in Computer Programming & Languages on Knoji.
Would you recommend this author as an expert in Computer Programming & Languages?
You have 0 recommendations remaining to grant today.
Comments (0)
ARTICLE DETAILS
RELATED ARTICLES
RELATED CATEGORIES