Functions

How do we use functions to manipulate data in Python?

KEY TERMS

  • Input/Parameter: the value or values you enter into a function

  • Output/Return: the value that the program gives you after it applies the function to the input/parameter

  • Built-in Functions: functions that are provided by Python to perform basic tasks

A function lets you make changes to data types (like integers, floats, and strings). Functions take in values and spit out ones that have been changed.

Similar to functions in math, functions built in programs take in an input value and do something to that input in order to create an output value. The function then returns (or spits out) the changed value. Most functions have a specific job to fulfill. For example, let's say we have defined a function called squared that takes in a number as its input value and returns that number squared as its output value. You can call a function by stating the function's name, and then putting your desired input values, or parameters, in parenthesis.

>>> squared(2)
4
>>> squared(3)
9

A function can also have multiple parameters (input values). For example, powers is a function that takes in two numbers. In the example, the first number (2) is being multiplied by itself the number of times given by the second parameter (3). Therefore, the function returns the result of 2 * 2 * 2. Notice that the order of the parameters is important here!

>>> powers(2, 3)
8 # 2 * 2 * 2
>>> powers(3, 2)
9 # 3 * 3

You do not have to worry about writing functions just yet, but you should understand what they do and how to use them. It's a good programming practice to give functions names that describe what they do to make the code easier to understand. In the first example, the function squaredhas a name that gives us a clue as to what is does. Remember, the whole point of programming is to make things easier!

Python has a few built-in functions that help us do simple things, like add numbers or find out how many items are in a list. You can think of these functions as a 'magic box' where you put something in and get something different out. For example, if you put in the integer 4 to the function str(), you'll get out '4'. Later, we will be writing our own functions. Below are some examples of built-in functions and what they can do. Start thinking about what you would want your own functions to do!

>>> str(4) # converting an integer to a string
'4'
>>> int('4') # converting a string to an integer
4
>>> float(4) # converting an integer to a float
4.0
>>> float('4') # converting a string to a float
4.0
>>> int(4.6) # converting a float to an int rounds down to the nearest whole number
4
>>> type('4') # tells you what data type something is
<type 'str'>
>>> type(4)
<type 'int'>
>>> type(4.0)
<type 'float'>

Last updated