In the script1204.py code, you define a function called dbl() that prompts for a number,
converts the answer to an integer, and then multiples it by 2 and returns it.
Then in the application part of the code, you call the dbl() function and assign its output to the
variable x. If you run the script1204.py script and enter a value at the prompt, you should see
these results:
Click here to view code image
pi@raspberrypi ~ $ python3 script1204.py
Enter a value: 10
doubling the value
The new value is 20
pi@raspberrypi ~ $
By the Way: Returning Values
In this example, the function returns an integer value, but you can also return strings,
floating-point values, and even other Python objects!
Passing Values to Functions
You might have noticed in the functions defined so far this hour that they have all created their own
data. However, most functions don’t operate in a vacuum but require information from the main
program to process. The following sections discuss how you can ensure that information gets to the
Python functions you create.
Passing Arguments
You pass values into a function from your main program by using arguments. Arguments are values
enclosed within the function parentheses, like this:
result = funct3(10, 50)
To retrieve the argument values in your Python functions, you define parameters in the function
definition. Parameters are variables you place in the function definition to receive the argument
values when the main program calls the function.
Here’s an example of defining a function that uses parameters:
>>> def addem(a, b):
result = a + b
return result
>>>
The addem() function defines two parameters. The a variable receives the first argument value, and
the b variable receives the second argument value. You can then use the a and b variables anywhere
within the function code.
Now when you call the addem() function from your Python code, you must pass two argument
values:
>>> total = addem(10, 50)
>>> print(total)
60