SoFunction
Updated on 2024-11-16

Python Function Usage Simple Examples [Definitions, Arguments, Return Values, Nested Functions

This article is an example of Python function usage. Shared for your reference, as follows:

(function definition):

# say_hello() # can't call a function before defining it
# The Python interpreter knows that a function is defined below
def say_hello():
  """Documentation of functions"""
  print("hello 1")
  print("hello 2")
  print("hello 3")
print("Before calling the function")
# Only in a program that actively calls a function to get it to execute
say_hello()
print("After the function is called")

Run results:

Before calling the function
hello 1
hello 2
hello 3
After calling the function

(function arguments, return values):

def sum_2_num(num1, num2):
  """Summing two numbers."""
  result = num1 + num2
  return result # Return results via return
# Variables can be used to receive the results of a function's execution.
sum_result = sum_2_num(10, 20)
print("Calculation: %d" % sum_result)

Run results:

Calculation: 30

(Nesting of functions):

def test1():
  print("*" * 50)
def test2():
  print("-" * 50)
  # Nested calls to functions
  test1()
  print("+" * 50)
test2()

Run results:

--------------------------------------------------
**************************************************
++++++++++++++++++++++++++++++++++++++++++++++++++

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.