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中,函數定義具有以下功能:
The keyword
def
關鍵字
def
- a function name 函數名稱
- paranthesis’()’, and within paranthesis input parameters,although the input parameters are optional. paranthesis'()'和在paranthesis輸入參數中,盡管輸入參數是可選的。
- a colon ’:’ 冒號':'
- some block of code to execute 一些要執行的代碼塊
- 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 * val2multiply(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 + bresult = 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 + bresult = 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 consoleprint(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 xprint(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 valueslist1 = [1, 2, 4, 5, 54]
print(max(list1)) # Returns 54 as 54 is the largest value in the listlist2 = ['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 steplist4 = []
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 valueslist1 = [1, 2, 4, 5, -54]
print(min(list1)) # Returns -54 as -54 is the smallest value in the listlist2 = ['a', 'b', 'c' ]
print(min(list2)) # Returns 'a' as 'a' is the smallest in the list in alphabetical orderlist3 = [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 steplist4 = []
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
時,該函數返回商和余數。 它使用兩個數字作為參數a
和b
。 參數不能為復數。
論據 (Argument)
It takes two arguments a
& b
- an integer, or a decimal number.It can’t be a complex number.
它a
兩個參數a
和b
整數或十進制數字,不能為復數。
返回值 (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.
返回值將是對由通過劃分獲得的商和余數的正數的a
由b
。 對于混合操作數類型,將應用二進制算術運算符的規則。對于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 list1str1 = 'basketball' # string
print(len(str1)) # prints 10 as the str1 is made of 10 characterstuple1 = (2, 3, 4, 5) # tuple
print(len(tuple1)) # prints 4 as there are 4 elements in the tuple1dict1 = {'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示例