Learning Python: Multiple Parameters in Functions, Local Variables, Type Hints, Return Values

Learning Python: Multiple Parameters in Functions, Local Variables, Type Hints, Return Values

Functions can accept more than one parameter. In this case, the parameters are separated by commas, both in the function definition and in the function call.

Example: Print the larger of two numbers.

>>> def print_larger(num1, num2):
...     if num1 > num2:
...         print(num1)
...     else:
...         print(num2)
... 

>>> print_larger(10, 20)
20        

Parameters can also be of different types.

Example: Print the given string given times.

>>> def string_multiply(string, repeat):
...     for i in range(repeat):
...         print(string)

>>> string_multiply("Hooray!", 3)
Hooray!
Hooray!
Hooray!        

Function parameters are often referred to as formal and?actual parameters. A formal parameter refers to a parameter variable used in the definition of a function. The actual value is the value that the parameter takes when the function is called.

In the previous example, string and repeat are formal parameters, Hooray! and 3 are actual parameters.


The variables initialized within a function are the local variables of the function. This means that they only exist during the execution of the function. This also applies to the parameters of the function.

NOTE: A function can have variables with the same name as the main program (or other functions). However, they are different variables.

Example: Show the difference between local function variable and main program variable.

def add_five(num):
    # num is a local variable in the function
    num += 5
    print("Function call value:", num)

# This is the main program's variable.
# It is different from the function's variable.
num = 10

print("Main program value before function call:", num)

add_five(20)

print("Main program value after the function call:", num)        

Output:

Main program value before function call: 10
Function call value: 25
Main program value after the function call: 10        

If you try to reference the local variables of a function from outside the function, an error will result.

Example: Try to reference a local variable outside the function.

def print_numbers(max):
    # This is a local variable.
    counter = 1
    while counter <= max:
        print(counter)
        counter +=1

# Call the function.
print_numbers(5)

# Attempting to reference the counter variable provides an error.
print(counter)        

Output:

1
2
3
4
5
Traceback (most recent call last):
  File "counter.py", line 11, in <module>
    print(counter)
NameError: name 'counter' is not defined        

However, variables in the main program can be referenced within a function.

Example: The main program variable is referenced inside a function.

def add_value(num):
    # The main program variable is added. 
    num += value
    print("Function call value:", num)

# This is the main program's variable.
value = 10

print("The main program variable:", value)

add_value(20)        

Output:

The main program variable: 10
Function call value: 30        

The main program variables can only be read within a function. An attempt to change the value will result in an error.

Example: Try to change the main program variable inside a function.

def add_value(num):
    # Change the main program variable.
    value += 100

    # The new value is added. 
    num += value

    print("Function call value:", num)

# This is the main program's variable.
value = 10

print("The main program variable:", value)

add_value(20)        

Output:

Traceback (most recent call last):
  File "link.py", line 15, in <module>
    add_value(20)
  File "link.py", line 3, in add_value
    value += 100        

As described earlier, the main program variable and the local variable can have the same name but they are different.

Example: The same variable name is defined in the main program and inside a function.

def add_value(num):
    # This is the local variable.
    value = 100

    print("The local variable:", value)

    # The new value is added. 
    num += value

    print("Function call value:", num)

# This is the main program's variable.
value = 10

print("The main program variable:", value)

add_value(20)        

Output:

The main program variable: 10
The local variable: 100
Function call value: 120        

Python does not specify the variable type, but the type is automatically derived based on the value placed in the variable. This can be problematic with functions.

Type hints can be defined for the function parameters, so that the caller knows what parameter type is expected.

NOTE: Type hints do not force the caller to use the correct type. Their role is to act as a comment-like hint as to which parameter types should be used.

Example:

>>> def string_multiply(string: str, repeat: int):
...     for i in range(repeat):
...         print(string)        

Functions can return a value when called, which can be stored in a variable. The value is returned by a return statement.

The clause immediately terminates the execution of the function and returns the execution to the caller. A return value corresponding to the result of the expression is included.

Example: Calculate and return the sum of the values received as parameters.

def sum(n: int, m: int):
    # Calculate the sum.
    sum = n + m

    # Return the sum.
    return sum

# Save the return value in a variable.
result = sum(10, 20)

print("The sum:", result)        

Output:

The sum: 30        

If nothing is done to the return value, it appears that the function does nothing at all.

Example: The return value is not stored in a variable.

def sum(n: int, m: int):
    # Calculate the sum.
    sum = n + m

    # Return the sum.
    return sum

# Call the function, but do nothing with the return value.
sum(10, 20)        

Output:

<no output>        

As mentioned, type hints do not force the use of the expected parameter types. The same function will execute with string values as well.

Example: Sum string values.

def sum(n: int, m: int):
    # Calculate the sum.
    sum = n + m

    # Return the sum.
    return sum

# Save the return value in a variable.
result = sum("foo", "bar")

print("The sum:", result)        

Output:

The sum: foobar        

It is important to understand the difference between a function returning something and a function printing something to the screen. This is often a difficult distinction to grasp when starting to program.

Example: Show the difference between printing a value and returning a value.

def print_larger(a: int, b: int):
    if a > b:
        print(a)
    else:
        print(b)

def return_larger(a: int, b: int):
    if a > b:
        return a
    else:
        return b

# Call the print function.
print_larger(10, 15)

# Call the return function.
# Store the return value to a variable.
larger = return_larger(100,200)

# Print the return value on the screen.
print("The return value:", larger)

# The return value can also be used in another context.
print("10 x return value: ", larger * 10)        

Output:

15
The return value: 200
10 x return value:  2000        

A type reference can also be assigned to the return value. The type hint informs the caller that the function returns a value of a certain type.

Example:

def return_larger(a: int, b: int) -> int:
    if a > b:
        return a
    else:
        return b        


Ioannis Theodoridis

Deputy Head of Networks Section at Bank of Greece. CCDevP, CCNP, Network Automation / Monitoring Specialist.

1 年

So nice to see this from you! I didn't catch the previous ones, I will make sure I do!!

要查看或添加评论,请登录

Riikka Sihvonen的更多文章

社区洞察

其他会员也浏览了