2.Functions and Getting Help
Functions and Getting Help
在本課中,我們將討論函數:調用它們,定義它們,并使用Python的內置文檔查找它們。
在某些語言中,定義函數必須要有特定的參數,每個參數都具有特定類型。 Python函數允許更靈活。 print函數就是一個很好的例子:
[1]
print("The print function takes an input and prints it to the screen.") print("Each call to print starts on a new line.") print("You'll often call print with strings, but you can pass any kind of value. For example, a number:") print(2 + 2) print("If print is called with multiple arguments...", "it joins them","(with spaces in between)", "before printing.") print('But', 'this', 'is', 'configurable', sep='!...') print() print("^^^ print can also be called with no arguments to print a blank line.") The print function takes an input and prints it to the screen. Each call to print starts on a new line. You'll often call print with strings, but you can pass any kind of value. For example, a number: 4 If print is called with multiple arguments... it joins them (with spaces in between) before printing. But!...this!...is!...configurable^^^ print can also be called with no arguments to print a blank line."What does this function do again?"
在前面的章節中我已經介紹了abs函數,但是如果你忘了它的作用怎么辦?
help()函數可能是你學習的最重要的Python函數。 如果你能記住如何使用help(),那么你就掌握了解Python中任何其他函數。
[2]
help(abs) Help on built-in function abs in module builtins:abs(x, /)Return the absolute value of the argument.應用于函數時,help()顯示...
- ???? 該函數的頭部為abs(x,/)。 在這種情況下,這告訴我們abs()采用單個參數x。 (正斜杠并不重要,但如果你很好奇,你可以在這里閱讀)
- ???? 關于該功能的簡要英文描述。
常見的陷阱:當你查找函數時,記得傳入函數本身的名稱,而不是調用該函數的結果。
如果我們在調用函數abs()時調用幫助會發生什么? 看看下面這個例子:
[3]
help(abs(-2)) Help on int object:class int(object)| int(x=0) -> integer| int(x, base=10) -> integer| | Convert a number or string to an integer, or return 0 if no arguments| are given. If x is a number, return x.__int__(). For floating point| numbers, this truncates towards zero.| | If x is not a number or if base is given, then x must be a string,| bytes, or bytearray instance representing an integer literal in the| given base. The literal can be preceded by '+' or '-' and be surrounded| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.| Base 0 means to interpret the base from the string as an integer literal.| >>> int('0b100', base=0)| 4| | Methods defined here:| | __abs__(self, /)| abs(self)| | __add__(self, value, /)| Return self+value.| | __and__(self, value, /)| Return self&value.| | __bool__(self, /)| self != 0| | __ceil__(...)| Ceiling of an Integral returns itself.| | __divmod__(self, value, /)| Return divmod(self, value).| | __eq__(self, value, /)| Return self==value.| | __float__(self, /)| float(self)| | __floor__(...)| Flooring an Integral returns itself.| | __floordiv__(self, value, /)| Return self//value.| | __format__(...)| default object formatter| | __ge__(self, value, /)| Return self>=value.| | __getattribute__(self, name, /)| Return getattr(self, name).| | __getnewargs__(...)| | __gt__(self, value, /)| Return self>value.| | __hash__(self, /)| Return hash(self).| | __index__(self, /)| Return self converted to an integer, if self is suitable for use as an index into a list.| | __int__(self, /)| int(self)| | __invert__(self, /)| ~self| | __le__(self, value, /)| Return self<=value.| | __lshift__(self, value, /)| Return self<<value.| | __lt__(self, value, /)| Return self<value.| | __mod__(self, value, /)| Return self%value.| | __mul__(self, value, /)| Return self*value.| | __ne__(self, value, /)| Return self!=value.| | __neg__(self, /)| -self| | __new__(*args, **kwargs) from builtins.type| Create and return a new object. See help(type) for accurate signature.| | __or__(self, value, /)| Return self|value.| | __pos__(self, /)| +self| | __pow__(self, value, mod=None, /)| Return pow(self, value, mod).| | __radd__(self, value, /)| Return value+self.| | __rand__(self, value, /)| Return value&self.| | __rdivmod__(self, value, /)| Return divmod(value, self).| | __repr__(self, /)| Return repr(self).| | __rfloordiv__(self, value, /)| Return value//self.| | __rlshift__(self, value, /)| Return value<<self.| | __rmod__(self, value, /)| Return value%self.| | __rmul__(self, value, /)| Return value*self.| | __ror__(self, value, /)| Return value|self.| | __round__(...)| Rounding an Integral returns itself.| Rounding with an ndigits argument also returns an integer.| | __rpow__(self, value, mod=None, /)| Return pow(value, self, mod).| | __rrshift__(self, value, /)| Return value>>self.| | __rshift__(self, value, /)| Return self>>value.| | __rsub__(self, value, /)| Return value-self.| | __rtruediv__(self, value, /)| Return value/self.| | __rxor__(self, value, /)| Return value^self.| | __sizeof__(...)| Returns size in memory, in bytes| | __str__(self, /)| Return str(self).| | __sub__(self, value, /)| Return self-value.| | __truediv__(self, value, /)| Return self/value.| | __trunc__(...)| Truncating an Integral returns itself.| | __xor__(self, value, /)| Return self^value.| | bit_length(...)| int.bit_length() -> int| | Number of bits necessary to represent self in binary.| >>> bin(37)| '0b100101'| >>> (37).bit_length()| 6| | conjugate(...)| Returns self, the complex conjugate of any int.| | from_bytes(...) from builtins.type| int.from_bytes(bytes, byteorder, *, signed=False) -> int| | Return the integer represented by the given array of bytes.| | The bytes argument must be a bytes-like object (e.g. bytes or bytearray).| | The byteorder argument determines the byte order used to represent the| integer. If byteorder is 'big', the most significant byte is at the| beginning of the byte array. If byteorder is 'little', the most| significant byte is at the end of the byte array. To request the native| byte order of the host system, use `sys.byteorder' as the byte order value.| | The signed keyword-only argument indicates whether two's complement is| used to represent the integer.| | to_bytes(...)| int.to_bytes(length, byteorder, *, signed=False) -> bytes| | Return an array of bytes representing an integer.| | The integer is represented using length bytes. An OverflowError is| raised if the integer is not representable with the given number of| bytes.| | The byteorder argument determines the byte order used to represent the| integer. If byteorder is 'big', the most significant byte is at the| beginning of the byte array. If byteorder is 'little', the most| significant byte is at the end of the byte array. To request the native| byte order of the host system, use `sys.byteorder' as the byte order value.| | The signed keyword-only argument determines whether two's complement is| used to represent the integer. If signed is False and a negative integer| is given, an OverflowError is raised.| | ----------------------------------------------------------------------| Data descriptors defined here:| | denominator| the denominator of a rational number in lowest terms| | imag| the imaginary part of a complex number| | numerator| the numerator of a rational number in lowest terms| | real| the real part of a complex numberPython從內到外評估這樣的表達式。 首先,它計算abs(-2)的值,然后它提供有關該表達式的任何值的幫助。
(事實證明有很多關于整數的說法!在Python中,即使是簡單的東西, 看起來像一個整數實際上也是一個具有相當大內部復雜性的對象。在稍后我們將討論Python中的對象,方法和屬性,上面的大量幫助輸出會更有意義。)
[4]
help(print) Help on built-in function print in module builtins:print(...)print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)Prints the values to a stream, or to sys.stdout by default.Optional keyword arguments:file: a file-like object (stream); defaults to the current sys.stdout.sep: string inserted between values, default a space.end: string appended after the last value, default a newline.flush: whether to forcibly flush the stream.其中一些可能看起來不可思議(什么是sys.stdout?),但是這個docstring確實揭示了我們在開頭的一個打印示例中使用的sep參數。
Defining functions
內置函數非常棒,但在我們需要定義自己的函數之前,我們只能使用它們。 下面是一個簡單的定義函數的例子。
[5]
def least_difference(a, b, c):diff1 = abs(a - b)diff2 = abs(b - c)diff3 = abs(a - c)return min(diff1, diff2, diff3)這里創建了一個名為least_difference的函數,有三個參數(a, b, c).
函數以def關鍵字開頭。 調用函數時會運行冒號后面: 的縮進代碼塊。
return是與函數唯一關聯的另一個關鍵字。 當Python遇到return語句時,它會立即退出函數,并將右側的值傳遞給調用上下文。
是否清楚了源碼中的least_difference()做了什么? 如果我們不確定,我們總是可以嘗試一些例子:
[6]
print(least_difference(1, 10, 100),least_difference(1, 10, 100),least_difference(5, 6, 7),#Python允許在參數列表中使用尾隨逗號,很有趣吧? ) 9 0 1或許help()函數可以告訴我們一些事情。
[7]
hep(least_difference) Help on function least_difference in module __main__:least_difference(a, b, c)不出所料,Python不夠聰明,無法讀取我的代碼并將其變成一個很好的英文描述。 但是,當我編寫一個函數時,我可以提供一個名為docstring的描述。
Docsting(文檔字符串)
[8]
def least_difference(a, b, c):"""Return the smallest difference between any two numbersamong a, b and c.>>> least_difference(1, 5, -5)4"""diff1 = abs(a - b)diff2 = abs(b - c)diff3 = abs(a - c)return min(diff1, diff2, diff3)docstring是一個三引號""""""字符串(可能跨越多行),緊跟在函數頭之后。 當我們在函數上調用help()時,它會顯示docstring。
[9]
help(least_difference) Help on function least_difference in module __main__:least_difference(a, b, c)Return the smallest difference between any two numbersamong a, b and c.>>> least_difference(1, 5, -5)4旁白:示例調用?docstring的最后兩行是示例函數調用和結果。 (>>>是對Python交互式shell中使用的命令提示符的引用。)Python不運行示例調用 - 它只是為了讀者的利益。 在函數的文檔字符串中包含一個或多個示例調用的約定遠非普遍觀察到,但它可以非常有效地幫助某人理解您的函數。 有關實際示例,請參閱numpy函數的docstring。
Docstrings是一種很好的方式來他人介紹你的代碼,甚至是你自己。 (你有多少次回到你前一天工作的一些代碼,并想知道“我在想什么?”)
Functions that don't return
如果在函數中不包含return關鍵字會怎么樣?
[10]
def least_difference(a, b, c):"""Return the smallest difference between any two numbersamong a, b and c."""diff1 = abs(a - b)diff2 = abs(b - c)diff3 = abs(a - c)min(diff1, diff2, diff3)print(least_difference(1, 10, 100),least_difference(1, 10, 10),least_difference(5, 6, 7), ) None None NonePython允許我們定義這樣的函數。 調用它們的結果是特殊值None。 (這與其他語言中的“null”概念類似。)
沒有return語句,least_difference是完全沒有意義的,但是帶有副作用的函數可以在不返回任何內容的情況下做一些有用的事情。 我們已經看到了兩個這樣的例子:print()和help()不返回任何內容。 我們調用它們只是為了副作用(在屏幕上放置一些文字)。 其他有用的副作用示例包括寫入文件或修改輸入。
[11]
mystery = print() print(mystery) NoneDefault arguments
當我們調用help(print)時,我們看到print函數有一些可選參數,例如,我們可以為sep指定一個值,在我們打印的參數之間添加一些特殊字符串:
[12]
print(1, 2, 3, sep=' < ')1 < 2 < 3但是如果我們不指定sep的值,sep默認值是空格' '。
[13]
print(1, 2, 3)1 2 3將可選參數的默認值添加到我們定義的函數中非常簡單:
[14]
def greet(who="Colin"):print("Hello,", who)greet() greet(who="Kaggle") # (In this case, we don't need to specify the name of the argument, because it's unambiguous.) greet("world") Hello, Colin Hello, Kaggle Hello, worldFunctions are objects too
[15]
def f(n):return n * 2x = 12.5創建它們的語法可能不同,但上面代碼中的f和x并沒有根本不同。 它們是每個對象的引用變量。 x指的是float類型的對象,f指的是......’類型的對象好吧,讓我們問Python:
[16]
print(type(x),type(f), sep='\n' ) <class 'float'> <class 'function'>我們甚至可以讓Python打印出f:
[17]
print(x) print(f)12.5 <function f at 0x7fbdb18040d0>......雖然它顯示的并不是非常有用。
請注意,上面的代碼單元有將另一個函數作為輸入的函數(type and print)的示例。 這開辟了一些有趣的可能性 - 我們可以將我們收到的函數作為參數調用。
[18]
def call(fn, arg):"""Call fn on arg"""return fn(arg)def squared_call(fn, arg):"""Call fn on the result of calling fn on arg"""return fn(fn(arg))print(call(f, 1),squared_call(f, 1), sep='\n', # '\n' is the newline character - it starts a new line ) 2 4您可能不會經常自己定義更高階的函數,但是有一些現有的函數(內置于Python和像pandas或numpy這樣的庫中),您可能會發現這些函數很有用。 例如,max函數。
默認情況下,max返回其最大的參數。 但是如果我們使用可選的key參數傳入一個函數,它會返回使key(x)最大的參數x。
[19]
def mod_5(x):"""Return the remainder of x after dividing by 5"""return x % 5print('Which number is biggest?',max(100, 51, 14),'Which number is the biggest modulo 5?',max(100, 51, 14, key=mod_5),sep='\n', ) which number is biggest? 100 Which number is the biggest modulo 5? 14Lambda functions
如果你正在編寫一個簡短的函數,它的主體是單行(如上面的mod_5),Python的lambda語法很方便。
[20]
mod_5 = lambda x: x % 5# Note that we don't use the "return" keyword above (it's implicit) # (The line below would produce a SyntaxError) #mod_5 = lambda x: return x % 5print('101 mod 5 =', mod_5(101)) 101 mod 5 = 1[21]
# Lambdas can take multiple comma-separated arguments abs_diff = lambda a, b: abs(a-b) print("Absolute difference of 5 and 7 is", abs_diff(5, 7)) Absolute difference of 5 and 7 is 2[23]
# Or no arguments always_32 = lambda: 32 always_32()32通過明智地使用lambdas,您可以偶爾在一行中解決復雜問題。
[23]
# Preview of lists and strings. (We'll go in depth into both soon) # - len: return the length of a sequence (such as a string or list) # - sorted: return a sorted version of the given sequence (optional key # function works similarly to max and min) # - s.lower() : return a lowercase version of string s names = ['jacques', 'Ty', 'Mia', 'pui-wa'] print("Longest name is:", max(names, key=lambda name: len(name))) # or just key=len print("Names sorted case insensitive:", sorted(names, key=lambda name: name.lower())) Longest name is: jacques Names sorted case insensitive: ['jacques', 'Mia', 'pui-wa', 'Ty']Your turn!
轉到練習筆記本,以獲得一些使用函數和獲得幫助實踐練習。
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的2.Functions and Getting Help的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: itouch.exe是什么进程 itou
- 下一篇: 11.29万起!大众全新宝来上市:全系取