The primary way to communicate with functions is arguments and return. Function arguments is how you pass information into a function. return is how a function passes information back.
To paraphrase some of the examples provide so far.
1 2 3 4 |
def func1(a, b):
return a + b
print (func1( 1 , 2 )
|
Line 1 is a function declaration. func1 has arguments a and b. They local variable created by Python when the function is called. They are assigned values that were passed by the caller of the function. In this example the func1() function is called in line 4. The value 1 is passed as the value for the argument a, and the value 2 is passed as the value for the argument b.
Line 2 computes the sum of a and b and returns this value. All functions return a value. If the function does not contain a "return" statement, the function returns None. In this example the function returns 3, the sum of the argument values 1 and 2.
There are other ways to get information into and out of a function, but arguments and return values are the most common, and the most preferred. Your program should be written like this:
1 2 3 4 5 6 7 |
def add_values(a, b):
return a + b
def print_value(value):
print (value)
print_value(add_values( 1 , 3 ))
|
This will print the number "4". If you change the arguments padded to add_values it will print a different number. This is what functions do. They perform an operation on input data. Change the input data an the function produces different results. That is why I did not use your function1. A function that always returns the same value should not be a function.
I also renamed your functions. Functions should not have names like function1 and function2. Functions should be named after what they do. My add_values adds two values and returns the sum. My print_value function print a value.
Another way to use the functions it to save the result of add_values in a variable and pass the variable to the print_value function.
1 2 3 4 5 6 7 8 |
def add_values(a, b):
return a + b
def print_value(value):
print (value)
a_plus_b = add_values( 1 , 3 )
print_value(a_plus_b)
|
You can also pass variables as arguments to a function.
1 2 3 4 5 6 7 8 9 10 |
def add_values(a, b):
return a + b
def print_value(value):
print (value)
a = 1
b = 3
a_plus_b = add_values(a, b)
print_value(a_plus_b)
|
Combining function calls with variables lets you perform complex, multi-part calculations.