8. Functions
8.1 function creation and call
def filterchar(string): import re pattern = r'(hacker)|(Grab bag)|(monitor)|(Trojan)' sub = re.sub(pattern, '@_@', string) print(sub) about = 'I'm a programmer. I like reading books about hackers. I want to study them Trojan. ' filterchar(about) # I'm a programmer. I like watching@_ @I want to study some books about@_ @.
8.2 transfer parameters
8.2.1 understand formal parameters and actual parameters
It can be divided into two cases: passing the value of the actual parameter to the formal parameter and passing the reference of the actual parameter to the formal parameter. When the actual parameter is an immutable object, value transfer is performed; when the actual parameter is a variable object, reference transfer is performed. After the value is passed, the value of the parameter is changed, and the actual parameter is unchanged; when the value of the parameter is passed, the actual parameter is also changed.
def demo(obj): print("original value is:", obj) obj += obj print("======== value passing ===============================") mot: 'only when you are chased can you really run' print('before function call: ', mot) demo(mot) print('after function call: ', mot) print("================================================================= list1 = ['xiaoming', 'lily', 'xiaohong'] print('before function call: ', list1) demo(list1) print('after function call: ', list1) ''' =======Value transfer===================== Before function call: only when you are chased can you really run The original value is: only when you are chased can you really run After function call: only when you are chased can you really run ===============Reference passing====================== Before function call: ['xiaoming ',' Lily ',' Xiaohong '] The original value is: ['xiaoming ',' Lily ',' Xiaohong '] After function call: ['xiaoming ',' Lily ',' Xiaohong ',' Xiaoming ',' Lily ',' Xiaohong '] '''
8.2.2 position parameters
- The location parameter must be the same as it was defined.
- Location must be the same as defined.
8.2.3 key parameters
The name of the utility parameter to determine the value of the input parameter. It does not need to be exactly consistent with the position of the formal parameter.
fun_bmi(person, height, weight) fun_bmi(height = 183, weight = 62, person = 'Xiaoming')
8.2.4 setting default values for parameters
def fun_bmi(height, weight, person = 'Xiaoming'): print(person + 'His height is:', weight, '\t The weight is:', weight) fun_bmi(185, 65) # Xiao Ming's height is 65 and his weight is 65
8.2.5 variable parameters
Called an indefinite length parameter, the actual parameters in the incoming function can be zero, one, two to any one.
- *parameter means that any number of actual parameters can be received and put into a tuple.
def printcoffee(*coffeename): print("my favorite coffee is:") for item in coffeename: print(item) printcoffee('Blue mountain ') printcoffee('cappuccino ',' Mocha ',' Manning ') ''' My favorite coffee is: Blue Mountain My favorite coffee is: Cappuccino Mocha Mandheling '''
- **parameter means to receive any number of actual parameters similar to keyword parameters to display the assignment and put them in a dictionary.
def printsign(**sign): print() for key, value in sign.items(): print("[" + key + "]The constellations of are:" + value) printsign(Qimeng = 'aquarius', Cold lemon = 'sagittarius') printsign(Xiangning = 'Pisces', Dylan = 'Gemini', Rice Noodles = 'Capricornus') ''' [Qimeng]The sign of Aquarius [Cold lemon]The sign of Sagittarius [Xiangning]The sign of Pisces [Dylan]The constellation of Gemini [Rice Noodles]The sign of Capricorn ''' dict1 = {'Xiangning':'Pisces', 'Dylan':'Gemini', 'Rice Noodles':'Capricornus'} printsign(**dict1) ''' [Xiangning]The sign of Pisces [Dylan]The constellation of Gemini [Rice Noodles]The sign of Capricorn '''
8.3 return value
def fun_check(money): money_old = sum(money) money_new = money_old if 500 <= money_old <= 1000: money_new = '{:.2f}'.format(money_old * 0.9) elif 1000 < money_old <= 2000: money_new = '{:.2f}'.format(money_old * 0.8) return money_old, money_new print('Start settlement.......\n') list_money = [] while True: inmoney = float(input('Enter item amount:')) if int(inmoney) == 0: break else: list_money.append(inmoney) money = fun_check(list_money) print('The total amount is:',money[0],"The amount payable is:", money[1]) ''' //Input commodity amount: 560 //Input commodity amount: 1200 //Enter product amount: 0 //Total amount: 1760.0 amount payable: 1408.00 '''
8.4 anonymous functions
A function without a name. Such a function is only used once. In python, use lambda expressions to create anonymous functions.
General code for calculating circle area:
import cmath def circlerear(r): result = cmath.pi * r * r return result r = 10 print('Radius is' + str(r) + 'The area of is:' + str(circlerear(r))) # The area of radius 10 is 314.1592653589793
The code to use the lambda expression is:
reslut = lambda r : cmath.pi * r * r print('Radius is' + str(r) + 'The area of is:' + str(reslut(r))) # The area of radius 10 is 314.1592653589793