函数及其参数(提高)

2023-12-05

Basic

Reference: Python Functions

Creating a Function

def my_function():
  print("Hello from a function") 

Calling a Function

调用上面定义过的函数 my_function():

my_function()

Arguments

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus") 

Number of Arguments

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil", "Refsnes") 
my_function("Emil")                #/// error, args not enough

Arbitrary Arguments *args

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus") 

Keyword Arguments

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") 

Arbitrary Keyword Arguments, **kwargs

def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes") 

#towork

Default Parameter Value

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil") 

Passing a List as an Argument

def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Return Values

def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9)) 

The pass Statement

def myfunction():
  pass

Recursion

def tri_recursion(k):
  if(k > 0):
    result = k + tri_recursion(k - 1)
    print(result)
  else:
    result = 0
  return result

print("\n\nRecursion Example Results")
tri_recursion(6)

更多可选参数实例

Ref: Optional Arguments in Python | Delft Stack

args arguments

def myfunction(first_name, last_name, *args):
    print(first_name)
    print(last_name)
    for argument in args:
        print(argument)


# Calling the Function
myfunction("Tim", "White", 999888999, 30)

#/// output
Tim
White
999888999
30

Keyword Arguments

def myFunction(**kwargs):
    # printing all values which are passed in as an argument
    for key, value in kwargs.items():
        print("%s = %s" % (key, value))


# Calling the Function
myFunction(first_name="Tim", last_name="White", mob=99999999, age="30")

#/// output
first_name = Tim
last_name = White
mob = 99999999
age = 30

Necessary position arguments

def personalDetails(name, number, age):
    print("This function takes 3 parameters as input")
    print("Name: ", name)
    print("Number: ", number)
    print("Age: ", age)


# Calling the function
personalDetails("Adam", 987654321, 18)

Optional arg

def personalDetails(name, number, age=0):
    print("Age is now an optional argument.")
    print("Age is: ", age)


# Calling the function
personalDetails("Sam", 123456789)


personalDetails("Sam", 123456789, 25)     #/// 结果和上一步有何区别?

Module

Reference: Python Modules

Create a Module

# mymodule.py

def greeting(name):  
  print("Hello, " + name)

Use / Import a Module

# another.py
import mymodule  
  
mymodule.greeting("Jonathan")

Variables in Module

# mymodule.py
person1 = {  
  "name": "John",  
  "age": 36,  
  "country": "Norway"  
}
# another.py
import mymodule  
  
a = mymodule.person1["age"]  
print(a)

这种方法也可以为程序配置参数。

Re-naming a Module

import mymodule as mx  
  
a = mx.person1["age"]  
print(a)

The dir() Function

import platform  
  
x = dir(platform)  
print(x)