Call Function:
#!/usr/bin/env Python3 #-*-coding:utf-8-*- # function call >>> abs (+) >>> abs ( -110) >>> ; ABS (12.34) 12.34 >>> ABS (1, 2) Traceback (most recent call last): File "
", line 1, in
C7/>typeerror:abs () takes exactly one argument (2 given) >>> abs (' a ') Traceback (most recent call last): Fil E "
", line 1, in
typeerror:bad operand type for abs (): ' Str ' >>> max (1, 2) 2 ;>> Max (2, 3, 1,-5) 3 >>> int (' 123 ') 123 >>> Int (12.34) >>> str (1.23) ' 1.23 ' >> > str ' + ' >>> bool (1) True >>> bool (") False >>> a = ABS # variable a points to ABS function, equivalent to reference >> > A (-1) # So you can also call the ABS function via a 1 >>> n1 = 255 >>> n2 = 0xFF >>> print (Hex (N1)), >> > Print (Hex (n2)) 0x3e8
To define a function:
#!/usr/bin/env Python3 #-*-coding:utf-8-*- #函数定义 def myabs (x): if x >= 0: return x else: return -X a = ten myabs (a) def NOP (): # NULL function
The pass statement does nothing.
In fact, pass can be used as a placeholder, such as not yet how to write the function code, you can write a pass, let the code run up.
If age >= 18:pass #缺少了pass, the code will have syntax errors >>> if age >= 18: ... File "
", line 2 ^ indentationerror:expected a indented block >>> myabs (1, 2) Traceback (most recent call last): F Ile "
", line 1, in
typeerror:myabs () takes 1 positional argument but 2 were given >>> myabs (' A ') Trac Eback (most recent): File "
", line 1, in file "
", Line 2, in Myabs TYP Eerror:unorderable types:str () >= int () >>> abs (' A ') Traceback (most recent call last): File "
", line 1, in
Typeerror:bad operand type for abs (): ' STR ' def myabs (x): If not isinstance (x, (int, float)): Raise TypeError (' bad operand type ') if x >= 0:return x else:return-x >>> myabs (' A ') Traceback (Mo St recent call last): File "
", line 1, in
file "
", L Ine 3, in Myabs typeerror:bad operand type
Return two values?
Import Math def move (x, y, step, angle = 0): NX = x + step * math.cos (angle) NY = y-step * Math.sin (angle) R Eturn NX, NY
In fact, the above is just an illusion, the Python function returned is still a single value.
Actually returned is a tuple!
However, syntactically, returning a tuple can omit parentheses, while multiple variables can accept a tuple at the same time, assigning the corresponding value by position.
Therefore, the Python function returns a multivalued value that actually returns a tuple, but it is easier to write.
Automatically return none when the function has finished executing and there is no return statement.
Practice:
Import Math def quadratic (A, B, c): x1 = (-B + Math.sqrt (b. * b-4 * A * C))/(2 * a) x2 = (-B-MATH.SQRT (b * b) -4 * A * C))/(2 * a) return x1, x2 x1, x2 = Quadratic (2, 5, 1) print (x1, x2) >>> Import Math >& Gt;> def quadratic (A, B, c): ... X1 = (-B + Math.sqrt (b. * b-4 * A * C))/(2 * a) ... x2 = (-B-MATH.SQRT (b * b-4 * A * C))/(2 * a) ... Return x1, x2 ... >>> x1, x2 = Quadratic (2, 5, 1) >>> print (x1, x2) -0.21922359359558485-2.280776406404 4154