Functions in Python can be easily defined and called upon throughout a directory of files as well as a single file itself. This tutorial will briefly demonstrate how Python functions work as well as defining a Python function.
The advantage of defining functions is that a script or application could be dealing with several instances of pretty much the same purpose. When you define a function, you can call it multiple times, thus eliminating the need for coding what the function does every time. Python has some pretty cool functions within its various imports which we will also look at.
Setting Up the Application
Go ahead and launch iPython Notebook. If you need a review of how the notebook works, feel free to check out here. Next, rename the program “Functions.”
Writing the Code
Next, we’re going to type in some code. I’ll explain what each element is responsible for later.
Now there are several other functions at play that we should address first. The function that we defined is called function1. The general organization of a function is:
#what variable does
In our above example, the user inputs two types of information: a number and a word. The raw_input() function is one way of getting the user to input information. Because our function is a function of 2 data types, we include a comma in between each component of the argument (the argument, for definition’s sake, is what is in between the parentheses next to a function).
Next, we want our function to do something. Our above function uses some external functions in part of its defintion. First we take use len(). What len() does is it takes the length of a string inputted and outputs its integer length. The next function is int(). The raw_input() function stores data as strings which cannot be added together (as they are not numbers – while they could be numbers, the computer doesn’t recognize them as numbers but rather as words or strings of letters). The function int() converts the variable within the argument to integer form (only if the argument is a number – you can’t convert a word to an integer).
The final part of our function adds the two numbers together. Then, it invokes print and returns the sum of x and y. But, this isn’t the end. We need to call our function. Defining the function only defines it; it doesn’t implement it. Thus, we use function1(word, number) to call the function on the various pieces of data inputted by the user.
And there we go! Functions in Python!