python示例_带有示例的Python功能指南

python示例

Python函数简介 (Introduction to Functions in Python)

A function allows you to define a reusable block of code that can be executed many times within your program.

函数允许您定义一个可重用的代码块,该代码块可以在程序中多次执行。

Functions allow you to create more modular and DRY solutions to complex problems.

通过函数,您可以为复杂问题创建更多的模块化和DRY解决方案。

While Python already provides many built-in functions such as print() and len(), you can also define your own functions to use within your projects.

尽管Python已经提供了许多内置函数,例如print()len() ,但您也可以定义自己的函数以在项目中使用。

One of the great advantages of using functions in your code is that it reduces the overall number of lines of code in your project.

在代码中使用函数的最大优点之一是,它减少了项目中代码的总行数。

句法 (Syntax)

In Python, a function definition has the following features:

在Python中,函数定义具有以下功能:

  1. The keyword def

    关键字def

  2. a function name

    函数名称
  3. paranthesis’()’, and within paranthesis input parameters,although the input parameters are optional.

    paranthesis'()'和在paranthesis输入参数中,尽管输入参数是可选的。
  4. a colon ’:’

    冒号':'
  5. some block of code to execute

    一些要执行的代码块
  6. a return statement (optional)

    返回语句(可选)
# a function with no parameters or returned values
def sayHello():
  print("Hello!")

sayHello()  # calls the function, 'Hello!' is printed to the console

# a function with a parameter
def helloWithName(name):
  print("Hello " + name + "!")

helloWithName("Ada")  # calls the function, 'Hello Ada!' is printed to the console

# a function with multiple parameters with a return statement
def multiply(val1, val2):
  return val1 * val2

multiply(3, 5)  # prints 15 to the console

Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegant code reuse without explicitly re-writing sections of code. This makes code both more readable, makes for easier debugging, and limits typing errors.

函数是可以简单地通过调用函数重用的代码块。 这样就可以简单,优雅地重用代码,而无需显式重写代码部分。 这使代码更易读,调试更轻松,并减少了键入错误。

Functions in Python are created using the def keyword, followed by a function name and function parameters inside parentheses.

Python中的函数是使用def关键字创建的,其后是括号内的函数名称和函数参数。

A function always returns a value,The return keyword is used by the function to return a value, if you don’t want to return any value, the default value None will returned.

函数总是返回一个值,该函数使用return关键字返回一个值,如果您不想返回任何值,则将返回默认值None

The function name is used to call the function, passing the needed parameters inside parentheses.

函数名称用于调用函数,并在括号内传递所需的参数。

# this is a basic sum function
def sum(a, b):
  return a + b

result = sum(1, 2)
# result = 3

You can define default values for the parameters, that way Python will interpretate that the value of that parameter is the default one if none is given.

您可以为参数定义默认值,这样,如果没有给出参数,Python将解释为该参数的值为默认值。

def sum(a, b=3):
  return a + b

result = sum(1)
# result = 4

You can pass the parameters in the order you want, using the name of the parameter.

您可以使用参数名称以所需顺序传递参数。

result = sum(b=2, a=2)
# result = 4

However, it is not possible to pass a keyword argument before a non-keyword one

但是,不可能在非关键字之前传递关键字参数

result = sum(3, b=2)
#result = 5
result2 = sum(b=2, 3)
#Will raise SyntaxError

Functions are also Objects, so you can assign them to a variable, and use that variable like a function.

函数也是对象,因此您可以将它们分配给变量,并像函数一样使用该变量。

s = sum
result = s(1, 2)
# result = 3

笔记 (Notes)

If a function definition includes parameters, you must provide the same number of parameters when you call the function.

如果函数定义包含参数,则在调用函数时必须提供相同数量的参数。

print(multiply(3))  # TypeError: multiply() takes exactly 2 arguments (0 given)

print(multiply('a', 5))  # 'aaaaa' printed to the console

print(multiply('a', 'b'))  # TypeError: Python can't multiply two strings

The block of code that the function will run includes all statements indented within the function.

该函数将运行的代码块包括该函数内缩进的所有语句。

def myFunc():
print('this will print')
print('so will this')

x = 7
# the assignment of x is not a part of the function since it is not indented

Variables defined within a function only exist within the scope of that function.

在函数中定义的变量仅存在于该函数的范围内。

def double(num):
x = num * 2
return x

print(x)  # error - x is not defined
print(double(4))  # prints 8

Python interprets the function block only when the function is called and not when the function is defined.So even if the function definition block contains some sort of error, the python interpreter will point that out only when the function is called.

Python仅在调用函数时才解释功能块,而在定义函数时才解释。因此,即使函数定义块包含某种错误,python解释器也只会在调用函数时指出该错误。

Now let's look at some specific functions with examples.

现在,让我们看一些带有示例的特定功能。

max()函数 (max() function)

max() is a built-in function in Python 3. It returns the largest item in an iterable or the largest of two or more arguments.

max()是Python 3中的内置函数。它返回可迭代的最大项或两个或多个参数中的最大项。

争论 (Arguments)

This function takes two or more numbers or any kind of iterable as an argument. While giving an iterable as an argument we must make sure that all the elements in the iterable are of the same type. This means that we cannot pass a list which has both string and integer values stored in it. Syntax: max(iterable, *iterables[,key, default]) max(arg1, arg2, *args[, key])

此函数将两个或多个数字或任何可迭代的数字作为参数。 在给出iterable作为参数时,我们必须确保iterable中的所有元素都属于同一类型。 这意味着我们无法传递同时存储字符串和整数值的列表。 语法:max(iterable,* iterables [,key,default])max(arg1,arg2,* args [,key])

Valid Arguments:

有效参数:

max(2, 3)
max([1, 2, 3])
max('a', 'b', 'c')

Invalid Arguments:

无效的参数:

max(2, 'a')
max([1, 2, 3, 'a'])
max([])

返回值 (Return Value)

The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. If the iterable is empty and default is not provided, a ValueError is raised.

返回迭代器中最大的项目。 如果提供了两个或多个位置参数,则返回最大的位置参数。 如果iterable为空且未提供默认值,则会引发ValueError

代码样例 (Code Sample)

print(max(2, 3)) # Returns 3 as 3 is the largest of the two values
print(max(2, 3, 23)) # Returns 23 as 23 is the largest of all the values

list1 = [1, 2, 4, 5, 54]
print(max(list1)) # Returns 54 as 54 is the largest value in the list

list2 = ['a', 'b', 'c' ]
print(max(list2)) # Returns 'c' as 'c' is the largest in the list because c has ascii value larger then 'a' ,'b'.

list3 = [1, 2, 'abc', 'xyz']
print(max(list3)) # Gives TypeError as values in the list are of different type

#Fix the TypeError mentioned above first before moving on to next step

list4 = []
print(max(list4)) # Gives ValueError as the argument is empty

Run Code

运行代码

Official Docs

官方文件

min()函数 (min() function)

min() is a built-in function in Python 3. It returns the smallest item in an iterable or the smallest of two or more arguments.

min()是Python 3中的内置函数。它返回可迭代的最小项或两个或多个参数中的最小项。

争论 (Arguments)

This function takes two or more numbers or any kind of iterable as an argument. While giving an iterable as an argument we must make sure that all the elements in the iterable are of the same type. This means that we cannot pass a list which has both string and integer values stored in it.

此函数将两个或多个数字或任何可迭代的数字作为参数。 在给出iterable作为参数时,我们必须确保iterable中的所有元素都属于同一类型。 这意味着我们无法传递同时存储字符串和整数值的列表。

Valid Arguments:

有效参数:

min(2, 3)
min([1, 2, 3])
min('a', 'b', 'c')

Invalid Arguments:

无效的参数:

min(2, 'a')
min([1, 2, 3, 'a'])
min([])

返回值 (Return Value)

The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional argumentsis returned. If the iterable is empty and default is not provided, a ValueError is raised.

返回iterable中的最小项。 如果提供了两个或多个位置自变量,则返回最小的位置自变量。 如果iterable为空且未提供默认值,则会引发ValueError。

代码样例 (Code Sample)

print(min(2, 3)) # Returns 2 as 2 is the smallest of the two values
print(min(2, 3, -1)) # Returns -1 as -1 is the smallest of the two values

list1 = [1, 2, 4, 5, -54]
print(min(list1)) # Returns -54 as -54 is the smallest value in the list

list2 = ['a', 'b', 'c' ]
print(min(list2)) # Returns 'a' as 'a' is the smallest in the list in alphabetical order

list3 = [1, 2, 'abc', 'xyz']
print(min(list3)) # Gives TypeError as values in the list are of different type

#Fix the TypeError mentioned above first before moving on to next step

list4 = []
print(min(list4)) # Gives ValueError as the argument is empty

Run Code

运行代码

Official Docs

官方文件

divmod()函数 (divmod() function)

divmod() is a built-in function in Python 3, which returns the quotient and remainder when dividing the number a by the number b. It takes two numbers as arguments a & b. The argument can’t be a complex number.

divmod()是Python 3中的内置函数,当将数字a除以数字b时,该函数返回商和余数。 它使用两个数字作为参数ab 。 参数不能为复数。

论据 (Argument)

It takes two arguments a & b - an integer, or a decimal number.It can’t be a complex number.

a两个参数ab整数或十进制数字,不能为复数。

返回值 (Return Value)

The return value will be the pair of positive numbers consisting of quotient and remainder obtained by dividing a by b. In case of mixed operand types, rules for binary arithmetic operators will be applied.For Integer number arguments, return value will be same as (a // b, a % b).For Decimal number arguments, return value will be same as (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that.

返回值将是对由通过划分获得的商和余数的正数的ab 。 对于混合操作数类型,将应用二进制算术运算符的规则。对于Integer number参数 ,返回值将与(a // b, a % b)对于Decimal number参数 ,返回值将与(q, a % b) ,其中q通常是math.floor(a / b),但可能比那小1。

代码样例 (Code Sample)

print(divmod(5,2)) # prints (2,1)
print(divmod(13.5,2.5)) # prints (5.0, 1.0)
q,r = divmod(13.5,2.5)  # Assigns q=quotient & r= remainder
print(q) # prints 5.0 because math.floor(13.5/2.5) = 5.0
print(r) # prints 1.0 because (13.5 % 2.5) = 1.0

REPL It!

替换它!

Official Docs

官方文件

Hex(x)函数 (Hex(x) function)

hex(x) is a built-in function in Python 3 to convert an integer number to a lowercase hexadecimal string prefixed with “0x”.

hex(x)是Python 3中的内置函数,用于将整数转换为以“ 0x”为前缀的小写十六进制字符串。

论据 (Argument)

This function takes one argument, x, that should be of integer type.

此函数采用一个参数x ,该参数应为整数类型。

返回 (Return)

This function returns a lowercase hexadecimal string prefixed with “0x”.

此函数返回以“ 0x”为前缀的小写十六进制字符串。

(Example)

print(hex(16))    # prints  0x10
print(hex(-298))  # prints -0x12a
print(hex(543))   # prints  0x21f

Run Code

运行代码

Official Documentation

官方文件

len()函数 (len() function)

len() is a built-in function in Python 3. This method returns the length (the number of items) of an object. It takes one argument x.

len()是Python 3中的内置函数。此方法返回对象的长度(项目数)。 它需要一个参数x

争论 (Arguments)

It takes one argument, x. This argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

它需要一个参数x 。 此参数可以是序列(例如字符串,字节,元组,列表或范围)或集合(例如字典,集合或冻结集合)。

返回值 (Return Value)

This function returns the number of elements in the argument which is passed to the len() function.

此函数返回传递给len()函数的参数中的元素数。

代码样例 (Code Sample)

list1 = [123, 'xyz', 'zara'] # list
print(len(list1)) # prints 3 as there are 3 elements in the list1

str1 = 'basketball' # string
print(len(str1)) # prints 10 as the str1 is made of 10 characters

tuple1 = (2, 3, 4, 5) # tuple 
print(len(tuple1)) # prints 4 as there are 4 elements in the tuple1

dict1 = {'name': 'John', 'age': 4, 'score': 45} # dictionary
print(len(dict1)) # prints 3 as there are 3 key and value pairs in the dict1

Run Code

运行代码

Official Docs

官方文件

奥德功能 (Ord function)

ord() is a built-in function in Python 3, to convert the string representing one Unicode character into integer representing the Unicode code of the character.

ord()是Python 3中的内置函数,用于将表示一个Unicode字符的字符串转换为表示该字符的Unicode代码的整数。

例子: (Examples:)
>>> ord('d')
100
>>> ord('1')
49

chr功能 (chr function)

chr() is a built-in function in Python 3, to convert the integer representing the Unicode code into a string representing a corresponding character.

chr()是Python 3中的内置函数,用于将表示Unicode代码的整数转换为表示相应字符的字符串。

例子: (Examples:)
>>> chr(49)
'1'

One thing is to be noted that, if the integer value passed to chr() is out of range then, a ValueError will be raised.

需要注意的是,如果传递给chr()的整数值超出范围,则将引发ValueError。

>>> chr(-10)
'Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    chr(-1)
ValueError: chr() arg not in range(0x110000)'

input()函数 (input() functions)

Many a time, in a program we need some input from the user. Taking inputs from the user makes the program feel interactive. In Python 3, to take input from the user we have a function input(). If the input function is called, the program flow will be stopped until the user has given an input and has ended the input with the return key. Let’s see some examples:

很多时候,在程序中,我们需要用户输入一些信息。 从用户那里获取输入使程序感到交互式。 在Python 3中,要获取用户的输入,我们有一个函数input() 。 如果调用了输入函数,则程序流程将停止,直到用户给出输入并以返回键结束输入为止。 让我们看一些例子:

When we just want to take the input:

当我们只想接受输入时:

这只会给出提示而没有任何消息 (This will just give a prompt without any message)

inp = input()

输入=输入()

Run Code

运行代码

To give a prompt with a message:

要提示信息:

promptwithmessage = input(’‘)

提示消息=输入(“”)

_ (_)

输出中的“ _”是提示 (The ’_’ in the output is the prompt)

Run Code

运行代码

3. When we want to take an integer input:

3.当我们要取整数输入时:

number = int(input('Please enter a number: '))

Run Code

运行代码

If you enter a non integer value then Python will throw an error ValueError. So whenever you use this, please make sure that you catch it too. Otherwise, your program will stop unexpectedly after the prompt.

如果输入非整数值,则Python将抛出错误ValueError因此,无论何时使用它,请确保您也抓住了它。 否则,提示后您的程序将意外停止。

number = int(input('Please enter a number: '))
# Please enter a number: as
# Enter a string and it will throw this error
# ValueError: invalid literal for int() with base 10 'as'

4. When we want a string input:

4.当我们想要一个字符串输入时:

string = str(input('Please enter a string: '))

Run Code

运行代码

Though, inputs are stored by default as a string. Using the str() function makes it clear to the code-reader that the input is going to be a ‘string’. It is a good practice to mention what type of input will be taken beforehand.

虽然,输入默认情况下存储为字符串。 使用str()函数可使代码阅读器清楚地知道输入将是“字符串”。 最好事先提及将采用哪种类型的输入。

Official Docs

官方文件

如何在Python中调用函数 (How to call a function in Python)

A function definition statement does not execute the function. Executing (calling) a function is done by using the name of the function followed by parenthesis enclosing required arguments (if any).

函数定义语句不执行该函数。 执行(调用)函数是通过在函数名称后加上括号将必需的参数(如果有)括起来来完成的。

>>> def say_hello():
...     print('Hello')
...
>>> say_hello()
Hello

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

函数的执行引入了一个新的符号表,用于该函数的局部变量。 更准确地说,函数中的所有变量分配都将值存储在本地符号表中。 而变量引用首先在本地符号表中查找,然后在封闭函数的本地符号表中查找,然后在全局符号表中查找,最后在内置名称表中查找。 因此,尽管可以引用全局变量,但不能在函数内直接为其赋值(除非在全局语句中命名)。

>>> a = 1
>>> b = 10
>>> def fn():
...     print(a)    # local a is not assigned, no enclosing function, global a referenced.
...     b = 20      # local b is assigned in the local symbol table for the function.
...     print(b)    # local b is referenced.
...
>>> fn()
1
20
>>> b               # global b is not changed by the function call.
10

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call.

函数调用的实际参数(参数)在被调用时被引入到被调用函数的本地符号表中。 因此,参数是通过按值调用(其中值始终是对象引用,而不是对象的值)传递的。 当一个函数调用另一个函数时,将为该调用创建一个新的本地符号表。

>>> def greet(s):
...     s = "Hello " + s    # s in local symbol table is reassigned.
...     print(s)
...
>>> person = "Bob"
>>> greet(person)
Hello Bob
>>> person                  # person used to call remains bound to original object, 'Bob'.
'Bob'

The arguments used to call a function cannot be reassigned by the function, but arguments that reference mutable objects can have their values changed:

用于调用函数的参数不能由该函数重新分配,但是引用可变对象的参数可以更改其值:

>>> def fn(arg):
...     arg.append(1)
...
>>> a = [1, 2, 3]
>>> fn(a)
>>> a
[1, 2, 3, 1]

翻译自: https://www.freecodecamp.org/news/python-function-guide-with-examples/

python示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值