# This is a learning note for the Liaoche teacher Python tutorial
1. Defining functions
defining a function requires a function name, a parameter, and a function body . In the function body, it is better to pass the parameter judgment.
1.1. Function creation
Define a function with Def, data type check with Isinstance. Examples are as follows:
def my_abs (x):
if not isinstance (x, (int, float)): # Determine the parameters passed in, whether it is xxx or floating-point
raise TypeError (' bad operand type ') # throws an error
If x >= 0:
return x
Else
Return-x
1.2. Empty function creation
If you want to define an empty function that doesn't do anything, you can use the PASS statement
Def NOP ():
Pass
The pass statement does nothing. When you're not sure how to write code, use it as a placeholder
1.3. Import of functions
You can import functions from a well-written. py script with import, or you can import the system's own modules to use the functions in the module
Importing system Modules
Import Math
After importing the Math module, we can use the MATH.SQRT () function
Import from A. py script (file name does not write suffix)
Form Test Import quadratic
From the test file, import the quadratic function
1.4. function returns multiple values
Defining functions
Import Math
def move (x, y, step, angle=0):
NX = x + step * Math.Cos (angle)
NY = y-step * Math.sin (angle)
Return NX, NY
Call
>>>x, y = Move (+, +, MATH.PI/6)
>>>print (x, y)
151.96152422706632 70.0
Explain
>>>r = Move (+, +, MATH.PI/6)
>>>print (R)
(151.96152422706632, 70.0)
Returning multiple function values is actually a tuple, which, in syntax, returns a tuple that can omit parentheses
1.5. Summary
When defining functions, it is necessary to determine the number of function names and parameters;
If necessary, the data type of the parameter can be checked first;
The function body can return the function result at any time with return;
Automatically return none when the function has finished executing and there is no return statement.
A function can return multiple values at the same time, but is actually a tuple.
2. Example
Defines a function quadratic (a, B, c), receives 3 parameters, returns a unary two-second equation:
AX2 + bx + c = 0 of two solutions.
Tip: Calculating the square root can call the Math.sqrt () function:
#!/usr/bin/env Python3
#-*-Coding:utf-8-*-
Import Math
def quadratic (a,b,c):
n = b*b-4*a*c # b*b = = b**2. Can be analogy b**3,b**4 .....
If n<0:
Print (' No real solution ')
Elif n==0:
x=-b/(2*a)
return x
Else
x1= (-B + math.sqrt (n))/(2*a)
X2= (-B-MATH.SQRT (n))/(2*a)
Return x1,x2
Python Learning note __2.2 defining functions