Ten minutes of Python introductory functions and modules

  Source code download

1. Function

A function is a block of code that only runs when called. You can pass data (called parameters) into functions.

Functions can return data as results.

Create function

In Python,  def functions are defined using keywords:

#在 Python 中,使用 def 关键字定义函数:
def my_function():
  print("Hello from a function")
#调用
my_function()
#输出:Hello from a function
parameter

Information can be passed to functions as parameters.

Parameters are specified within parentheses after the function name. You can add as many parameters as you need, just separate them with commas.

#参数
def my_function(fname):
  print('您好' + fname )

my_function("小明")
#输出:您好小明
Default parameter value

If we call the function without parameters, the default values ​​are used:

#如果我们调用了不带参数的函数,则使用默认值:
def my_function(country = "China"):
  print("I am from " + country)

my_function("India")
#输出:I am from India
my_function()
#输出:I am from China
Pass parameters as List

The arguments you send to the function can be of any data type (string, number, list, dictionary, etc.) and they will be treated as the same data type within the function.

#函数的参数可以是任何数据类型(字符串、数字、列表、字典等),并且在函数内其将被视为相同数据类型。
def my_function(food):
  for x in food:
    print(x)

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

my_function(fruits)
#输出:apple banana cherry
return value

To make a function return a value, use  return the statement:

#如需使函数返回值,请使用 return 语句:
def my_function(x):
  return 5 * x

print(my_function(4))
#输出:20
keyword arguments

You can also send parameters using key = value syntax. The order of parameters does not matter.

#您还可以使用 key = value 语法发送参数。参数的顺序无关紧要。
def my_function(child3, child2, child1):
  print("你好" + child3)

my_function(child1 = "小明", child2 = "小红", child3 = "小黑")
#输出:你好小黑
any parameter

If you don't know how many parameters will be passed to your function, add * in front of the parameter names of the function definition.

This way, the function receives a tuple of arguments and can access the items accordingly:

#如果您不知道将传递给您的函数多少个参数,请在函数定义的参数名称前添加 *
def my_function(*kids):
  print("你好 " + kids[2])

my_function("小明", "小红", "小黑")
#输出:你好 小黑
recursion

Python also accepts function recursion, which means that a defined function can call itself.

#Python 也接受函数递归,这意味着定义的函数能够调用自身。
def tri_recursion(k):
  if(k>0):
    result = k+tri_recursion(k-1)
    print(result)
  else:
    result = 0
  return result

tri_recursion(6)
#输出:1 3 6 10 15 21
 Advanced usage of functions @call
#函数调用高级用法
def new_tips(argv):
  def tips(func):
    def nei(a, b):
      print('start %s %s' % (argv, func.__name__))
      func(a, b)
      print('stop')

    return nei
  return tips

# 执行add函数时调用new_tips函数
@new_tips('add_module')
def add(a, b):
  print(a + b)


print(add(4, 5))
#输出: start add_module add  9 stop None

Python modules

A module is a file that contains a set of functions that you wish to reference in your application.

Create module

To create a module, simply save the required code in  .py a file with the file extension:

mymodule.py Save the code in a file named

#模块
def greeting(name):
  print("Hello, " + name)
Use modules

Now, we can use  import the module we just created using statements:

#导入名为 mymodule 的模块,并调用 greeting 函数
import mymodule

mymodule.greeting("小明")
#输出:Hello, 小明

If you use a function from a module, use the following syntax:

module_name.function_name
Variables in modules

Modules can contain functions as already described, but they can also contain variables of various types (arrays, dictionaries, objects, etc.):

mymodule.py Save the code in a file  :

#模块中的变量
person1 = {
  "姓名": "小明",
  "年龄": 11,
  "国家": "china"
}

Import  mymodule the module named and access the person1 dictionary:

#导入名为 mymodule 的模块,并访问 person1 字典:
import mymodule
a = mymodule.person1["年龄"]
print(a)
#输出:11
Rename module

as You can create aliases using keywords when importing a module  :

#为 mymodule 创建别名 mx:
import mymodule as mx

a = mx.person1["姓名"]
print(a)
#输出:小明
Built-in modules

There are several built-in modules in Python that you can import at any time.

#Python 中有几个内建模块,您可以随时导入。
import platform

x = platform.system()
print(x)
#输出:Windows
Use dir() function

There is a built-in function that lists all function names (or variable names) in a module. dir() function:

#列出属于 platform 模块的所有已定义名称
import platform

x = dir(platform)
print(x)

import from module

You can choose to import parts only from modules using the from keyword.

#从模块导入部件
from mymodule import person1

print(person1["年龄"])
#输出:11

If this document is not detailed enough, you can refer to learn python in ten minutes_bilibili_bilibili​

Guess you like

Origin blog.csdn.net/kan_Feng/article/details/131919399