1. Experimental content: Examples and actual combat in Chapter 6 of "Zero Basic Python", as well as a homework problem
2. Experimental environment: IDLE Shell 3.9.7
3. Experimental purpose and requirements: master the definition and call function, the scope of variables, anonymous functions, parameter passing, return values, etc.
4. Experimental content:
- Homework 01
Write a program to determine whether the entered phone number is China Unicom, China Telecom or China Mobile
Full code:
,import re pattern1=r'(13[4-9]\d{8})$|(14[78]\d{8})$|(15[012789]\d{8})$|(17[28]\d{8})$|(18[23478]\d{8})$|(19[578]\d{8})$' pattern2=r'(13[3]\d{8})$|(14[9]\d{8})$|(17[37]\d{8})$|(18[019]\d{8})$|(19[0139]\d{8})$' pattern3=r'(13[0-2]\d{8})$|(14[56]\d{8})$|(16[6]\d{8})$|(17[56]\d{8})$|(18[56]\d{8})$|(19[6]\d{8})$' mobile=input( ) yd=re.match(pattern1,mobile) dx=re.match(pattern2,mobile) lt=re.match(pattern3,mobile) if yd==None and dx==None and len(mobile)==11: print(mobile,'It's China Unicom's phone number') elif yd==None and lt==None and len(mobile)==11: print(mobile,'It's China Telecom's phone number') elif dx==None and lt==None and len(mobile)==11: print(mobile,'It's China Mobile's phone number') else: print('Please enter an 11-digit mobile number')
operation result:
- Example 01 Output a daily post (shared version)
Create a file named function_tips.py in IDLE, then create a function named function_tips in the file, in this function, get a motivational text from the list of motivational texts and output, and finally call the function function_tips() ,code show as below:
,def function_tips(): '''Function: output a motivational text every day ''' import datetime #import datetime class #define a list mot=["today is Monday:\n Hold on not because I'm strong, but because I have no choice", "Today is tuesday:\n Those who sow with tears will surely reap with a smile", "Today is Wednesday:\n Doing the right thing is more important than doing the right thing", "Today is thursday:\n What fate gives us is not the wine of disappointment, but the cup of opportunity", "today is Friday:\n Don't wait until tomorrow, tomorrow is too far away, act today", "today is Saturday:\n If you are hungry for knowledge, you are humble in heart", "today saturday:\n Success belongs to those who never say "impossible"" ] day=datetime.datetime.now().weekday() #get current date print(mot[day]) #output one post per day #*******************************Call functions***************** **************** function_tips()
operation result:
- Example 02 Calculate BMI index based on height and weight (shared version)
Create a file named function_bmi.py in IDLE, and then define a function named fun_bmi in the file. The function includes 3 parameters, which are used to specify name, height and weight respectively. According to the formula: BMI=weight /(Height×Height) Calculate the BMI index and output the result. Finally, the fun_bmi function is called twice outside the function. The code is as follows:
,def fun_bmi(person,height,weight): '''Function: Calculated according to height and weight BMI index person:Name height:Height in meters weight:Weight in kilograms ''' print(person+'height:'+str(height)+'Meter\t weight:'+str(weight)+'kilogram') bmi=weight/(height*height) print(person+'of BMI The index is:'+str(bmi)) #Determine whether the body is reasonable if bmi<18.5: print("you are underweight~@_@~") if bmi>=18.5 and bmi<24.9: print("normal range, please keep(-_-)") if bmi>=24.9 and bmi<29.9: print("you are overweight~@_@~") if bmi>=29.9: print("obesity^@_@^") #*********************Call functions********************* fun_bmi("Passerby",1.83,60) fun_bmi("Passerby B",1.60,50)
operation result:
- Example 03 Calculate BMI index based on height and weight (shared upgraded version)
Create a file named function_bmi_upgrade.py in IDLE, and then define a function named fun_bmi_upgrade in the file, which includes a variable parameter to specify the test person information including name, height and weight, in the In the function, the BMI index will be calculated according to the tester information, and the result will be output. Finally, a list is defined outside the function, and the list is called as a parameter of the fun_bmi_upgrade() function. The code is as follows:
,def fun_bmi_upgrade(*person): '''Function: Calculated according to height and weight BMI index *person:Variable parameter This parameter needs to pass a list with 3 elements, Name, height (unit: meters) and weight (unit: kilograms) ''' for list_person in person: for item in list_person: person=item[0] height=item[1] weight=item[2] print("\n"+"="*13,person,"="*13) print('height:'+str(height)+'Meter\t weight:'+str(weight)+'kilogram') bmi=weight/(height*height) print('BMI index:'+str(bmi)) #Determine whether the body is reasonable if bmi<18.5: print("you are underweight~@_@~") if bmi>=18.5 and bmi<24.9: print("normal range, please keep(-_-)") if bmi>=24.9 and bmi<29.9: print("you are overweight~@_@~") if bmi>=29.9: print("obesity^@_@^") #*********************Call functions********************* list_w=[('dream',1.70,65),('Zero language',1.78,50),('Dailan',1.72,66)] list_m=[('Zi Xuan',1.80,75),('Leng Yiyi',1.75,70)] fun_bmi_upgrade(list_w,list_m)
operation result:
- Example 04 Simulated checkout function - calculation of actual payment amount
,def fun_checkout(money): '''Function: Calculate the total amount of goods and process discounts money:Save a list of item amounts Returns the total amount and discounted amount of the item ''' 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) elif 2000<=money_old<=3000: money_new='{:.2f}'.format(money_old*0.7) elif money_old>=3000: money_new='{:.2f}'.format(money_old*0.6) return money_old,money_new #*******************Call functions********************* print("\n start billing......\n") list_money=[] while True: inmoney=float(input("Enter the item amount(Enter 0 to indicate that the input is complete):")) if int(inmoney)==0: break else: list_money.append(inmoney) money=fun_checkout(list_money) print("Total Amount:",money[0],"Amounts payable:",money[1])
operation result:
- Example 05 A pine tree's dream
,pinetree='i am a pine tree' def fun_christmastree(): '''Function: a dream no return value ''' pinetree='Hang lanterns and gifts......I became a Christmas tree@^.^@\n' print(pinetree) #********************FUNCTION EXTERNAL ******************** print('\n Snowing......\n') print('==========start dreaming......===========\n') fun_christmastree() print('==========wake up......=============\n') pinetree='snowflakes all over me,'+pinetree+'-_-' print(pinetree)
operation result:
- Example 06 Applying lambda to sort the crawled seckill product information
,bookinfo=[('different carmela(full set)',22.50,120),('zero foundation Andoid',65.10,89.80), ('ferryman',23.40,36.00),('The Complete Works of Sherlock Holmes 8 Volumes',22.50,128)] print('Crawled product information:\n',bookinfo,'\n') bookinfo.sort(key=lambda x:(x[1],x[1]/x[2])) print('Sorted product information:\n',bookinfo)
operation result:
- Actual combat 01 The director chooses the protagonist for the script
code show as below:
,def director_lead(*zj ): '''Function: Output to determine the name of the protagonist participating in the script ''' for item in zj: print(item) zj=input('The protagonists chosen by the director are:') print(str(zj)+"start the script")
operation result:
- Actual combat 02 Simulate the package of Meituan takeaway merchants
code show as below:
,def Mtpackage(*packagename): print('\n The rice noodle shop package is as follows: 1.Test God Package 2.Single Package 3.couple package') for item in packagename: print(item) param=['Kao God package 13 yuan','Single Package 9.9 Yuan','Couple package 20 yuan'] Mtpackage(*param)
operation result:
- Actual combat 03 Judging the constellation according to the birthday
code show as below:
,def birthday_constellation(month,date): '''Function: According to the birthday, you can determine the constellation you belong to month: variable to store month date:variable to store date list_star:Store a list of constellations ''' list_star=['Capricornus','Aquarius','Pisces','Aries','Taurus','Gemini', 'Cancer','Leo','Virgo','Libra','Scorpio','Sagittarius','Capricornus'] list_month= (20,19,21,20,21,22,23,23,23,24,23,22) if date<list_month[month-1]: return list_star[month-1] else: return list_star[month] month=int(input('Please enter month(E.g:5)')) date=int(input('Please enter a date(E.g:17)')) print(str(month)+'moon'+str(date)+'The constellation of the sun is:',birthday_constellation(month,date))
operation result:
- Practical 04 Convert USD to RMB
code show as below:
,def dollar_RMB( my ): '''Function: Convert the US dollar according to the exchange rate "1 US dollar=6.28 Convert "RMB" to RMB ''' rmb=my*6.28 return rmb my=int(input('Please enter the dollar amount to convert:')) print('The converted RMB amount is:',dollar_RMB(my))
operation result: