SoFunction
Updated on 2024-11-10

Python learning notes of the definition of the function and the scope of the example details

This article is an example of the definition and scope of Python functions. Shared for your reference, as follows:

Defining Functions

Default Arguments: You can add default arguments to a function to provide default values for arguments that are not specified in the function call.

# If the cylinder_volume function is called without the radius parameter, then the value of radius is 5
def cylinder_volume(height, radius=5):
  pi = 3.14159
  return height * pi * radius ** 2

Methods for passing values to parameters in functions: by position and by name

cylinder_volume(10, 7) # 1539.3791
cylinder_volume(height=10, radius=7) # 1539.3791
cylinder_volume(radius=7, height=10) # 1539.3791

Note: The first of the above is commonly used to pass values by location, while the second and third are passed by name.

Defining Functions [Related Exercise]

Write a function named population_density that takes two arguments, population and land_area, and returns the population density based on those two values.

Solution:

def population_density(population, land_area):
  return population / land_area
test1 = population_density(10, 1)
expected_result1 = 10
print("expected result: {}, actual result: {}".format(expected_result1, test1)) # expected result: 10, actual result: 10.0
test2 = population_density(864816, 121.4)
expected_result2 = 7123.6902801
print("expected result: {}, actual result: {}".format(expected_result2, test2)) # expected result: 7123.6902801, actual result: 7123.690280065897

Write a function called readable_timedelta that takes one argument: the integer days, and returns a string representing the number of weeks and days. For example, readable_timedelta(10) should return "1 week(s) and 3 day(s)." .

Solution:

def readable_timedelta(days):
  weeks = int(days / 7)
  day = days % 7
  return str(weeks) + ' week(s) and ' + str(day) + ' day(s).'
print(readable_timedelta(10)) # 1 week(s) and 3 day(s).

Variable scoping in functions

  • Variable scoping refers to the part of the program in which a variable can be referenced or used.
  • When using a variable within a function, it is important to consider the scope. If the variable is created inside a function, you can only use the variable inside that function. You cannot access the variable from outside that function.

Example of an error:

# This will result in an error
def some_function():
  word = "hello"
print(word)

This means that you can use the same name for different variables used in different functions, as shown in the correct example below:

def some_function():
  word = "hello"
def another_function():
  word = "goodbye"

Variables defined outside of a function can still be accessed within the function.

word = "hello"
def some_function():
  print(word)
print(word)

Best Practise: It is recommended that variables be defined in the smallest scope required. Although functions can reference variables defined in larger scopes, this is usually not recommended because if the program has many variables, you may not know what variables you have defined.

take note of: Python does not allow functions to modify variables that are not in the function's scope; execute the following code and see what happens

egg_count = 0
def buy_eggs():
  egg_count += 12 # purchase a dozen eggs
buy_eggs()

An error occurs, resulting in UnboundLocalError : We will encounter this error when we try to change or reassign the value of a variable outside a function to another value, but this principle applies only to integers and strings, lists, dictionaries, sets, classes can be modified in subroutines (subfunctions) by modifying local variables for the purpose of modifying global variables.

For those interested in Python-related content, check out this site's feature: theSummary of Python function usage tips》、《Python Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python string manipulation techniques》、《Summary of Python coding manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.