Business data analysis from entry to entry (6) Python program structure and function

CuterCorley 2021-04-05 22:22:37
business data analysis entry entry


One 、Python Program structure

Python in , Yes 3 A common program structure :

  • Sequence From top to bottom .
  • Condition If a condition satisfies a certain condition, execute .
  • Loop Repeat an action in a loop .

1.if Conditions

To judge whether a variable meets a certain condition, it is as follows :

possibility_to_rain = 0.7print(possibility_to_rain > 0.8)print(possibility_to_rain > 0.3)possibility_to_rain = 1print(possibility_to_rain > 0.8)print(possibility_to_rain > 0.3)

Output :

FalseTrueTrueTrue

To synchronize this section ipynb file , You can click add directly QQ Group Python Geek tribe 963624318 In the group folder Business data analysis from entry to entry You can download it in .

But if you want to perform an action when a variable satisfies a certain condition , You need to if Conditional statements , as follows :

possibility_to_rain = 0.7if possibility_to_rain > 0.8: print("Do take your umberalla with you.") ## The standard format here is an indent of four spaces elif possibility_to_rain > 0.3: print("Take your umberalla just in case. hahaha") else: print("Enjoy the sunshine!")print('hello')

Output :

Take your umberalla just in case. hahaha

This code means : If possibility_to_rain > 0.8 by True, execute print("Do take your umberalla with you."), If the above conditions are not met , But satisfied possibility_to_rain > 0.3, execute print("Take your umberalla just in case. hahaha"), Otherwise execution print("Enjoy the sunshine!");if After statement execution , After the statement is executed , Such as print('hello'); We need to pay attention to Indent ,if、elif、else Statements after statements should be indented 4 Check and keep aligned , That is to control code block and code structure through indentation , Unlike other languages {} To control the code structure , as follows :python code blocks

We can see it in the front , There's a lot to # The beginning of the code and text description , Code color is also different from other codes , This is it. Python A single line comment in , Annotated code is not executed , But it can only play an illustrative role , In this code The standard format here is an indent of four spaces By # notes , The code in front of this line works properly ,# The following text will not be executed 、 No errors reported 、 As an explanatory statement .

In addition to judging the value , You can also judge strings :

card_type = "debit"account_type = "checking"if card_type == "debit": if account_type == "checking": print("Checkings selectd.") else: print("Savings selected.")else: print("Credit card.")

Output :

Take your umberalla just in case. hahahahello

You can see , Using the conditional judgment nesting .

2. loop

while loop

If you need to repeat before , May be the following :

count =1print(count)count+=1print(count)count+=1print(count)count+=1print(count)count+=1print(count)count+=1print(count)count+=1print(count)count+=1print(count)count+=1print(count)count+=1print(count)

Output :

12345678910

obviously , The code is long , At this point, you can use the loop to optimize .

Use while The cycle is as follows :

count = 1while count <= 10: print(count) count += 1

The execution effect is the same as before ; We need to pay attention to , The cycle usually has to have The conditions for stopping , When satisfied count <= 10 The loop will be executed all the time , until count = 11 It doesn't fit 、 So you can exit the loop ; If there is no stop condition , You may fall into a dead cycle 、 Memory consumption .

Again :

cnt = 1while True: print("cnt = %d" % cnt) ch = input('Do you want to continue? [y:n]: ') if ch == 'y': cnt += 1 else: break 

Output is as follows :python while loop break

You can see , Although the cycle condition is True, It's permanent , But there's a condition judgment inside the loop , The input is y It's going to keep cycling , Enter others and execute break Exit loop ; But we need to pay attention , There's only strict input here y To continue the cycle , But input yes Will exit the cycle , So to further control the running logic 、 We also need to improve the code .

stay Python in ,else with while Recycling in combination , If the loop is not called break And the end , Will perform else The statement in , This can be used to determine if the loop is fully executed , For example, the first 1 Is the example of a loop running 10 Time .

as follows :

count = 1while count < 11: print(count) count = count + 1else: print('Counting complete.') print()count = 1while count < 11: print(count) count = count + 1 if count == 8: breakelse: print('Counting complete.')

Output :

12345678910Counting complete.1234567

You can see : The first cycle didn't because break And stop the cycle , So after the loop statement is executed else sentence ; The second cycle is because count by 8 Time to satisfy if Condition and exit the loop 、 The loop is not finished , Therefore, it is not implemented else sentence .

Again :

count=0while count < 11: print("while count:",count) count = count + 1 if count == 11: breakelse: print("else:",count)

Output :

while count: 0while count: 1while count: 2while count: 3while count: 4while count: 5while count: 6while count: 7while count: 8while count: 9while count: 10

obviously , At this point, because the execution of the last loop satisfies if It's a condition of execution break sentence , Therefore, it has not been implemented else Sentence block .

for loop

Often with for There's also a cycle of range,range(self, /, *args, **kwargs) Functions have two common uses :

range(stop) -> range objectrange(start, stop[, step]) -> range object

This function returns an object , The object is represented by step Generate from for step size start( contain ) To stop( exclude ) Of Sequence of integers . for example range(i, j) produce i,i+1,i+2,…,j-1 Sequence .

Input :

for i in range(10): print(i)

Output :

0123456789

Again :

for i in range(4,10): print(i)print()for i in range(4,10,2): print(i)print()for i in range(5): print('Corley')print()for i in range(5): print('Corley'[i])

Output :

456789468CorleyCorleyCorleyCorleyCorleyCorle

You can see ,for Loop can also be executed with i Unrelated operations ; It can also be used to traverse strings .

for It can also be used in the loop break Statement to terminate the loop , as follows :

for i in range(10): print(i) if i == 5: break

Output :

012345

Again :

result = 0for num in range(1,100): if num % 2 == 0: result = result + numprint(result)

Output :

2450

The above example implements the calculation from 1 To 100( barring ) All even sums of .

3. Case study - Wang Rongyao's pure text analysis

The goal is to extract all the hero information links from the following text 、 Avatar image link 、 Hero name , Such as herodetail/194.shtml、http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg And sully :

<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt=" Su lie "> Su lie </a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt=" Hundred Li xuance "> Hundred Li xuance </a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt=" Hundred Li keep the promise "> Hundred Li keep the promise </a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt=" armoured "> armoured </a></li></ul>

We can find a hero's message first , That is to use subscript for string segmentation , Use when looking for subscripts find() Method . for example , For links http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg, If you find the first one h The letter and the last g The subscript of the letter , You can extract the link through segmentation .

Read in the string first , as follows :

page_hero = '''<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt=" Su lie "> Su lie </a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt=" Hundred Li xuance "> Hundred Li xuance </a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt=" Hundred Li keep the promise "> Hundred Li keep the promise </a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt=" armoured "> armoured </a></li></ul>'''

At this time, we can get the subscript of the character related to the target step by step and get the target string according to the subscript slice , For example, the link to get the picture is as follows :

start_link = page_hero.find('<img src="')print(start_link)start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_link = page_hero[start_quote+1:end_quote]print(hero_link)

Output :

81http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg

At this point, get the hero's name and information in turn, and the link is as follows :

# The first 1 A hero start_link = page_hero.find('<a href="')start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_info1 = page_hero[start_quote+1:end_quote]print(hero_info1)start_link = page_hero.find('<img src="', end_quote+1)start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_link1 = page_hero[start_quote+1:end_quote]print(hero_link1)end_bracket = page_hero.find('>', end_quote+1)start_bracket = page_hero.find('<', end_bracket+1)hero_name1 = page_hero[end_bracket+1:start_bracket]print(hero_name1)

Output :

herodetail/194.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg Su lie 

obviously , Has obtained the 1 Complete information about a hero .

At this time, we can get the second 2 A hero's message , as follows :

# The first 2 A hero page_hero = page_hero[start_bracket:]start_link = page_hero.find('<a href="')start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_info2 = page_hero[start_quote+1:end_quote]print(hero_info2)start_link = page_hero.find('<img src="', end_quote+1)start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_link2 = page_hero[start_quote+1:end_quote]print(hero_link2)end_bracket = page_hero.find('>', end_quote+1)start_bracket = page_hero.find('<', end_bracket+1)hero_name2 = page_hero[end_bracket+1:start_bracket]print(hero_name2)

Output :

herodetail/195.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg Hundred Li xuance 

We need to pay attention to : The second segmentation does not need to be performed on the original string 、 As long as you start to search and segment from the position of the last segmentation , therefore page_hero = page_hero[end_quote:] That is to reassign the substring after the last segmentation to page_hero As a new string ; Because the string form of each hero's information is the same , So you can directly use the way to find the first hero .

Find the first 3 And the first 4 A hero is like this :

# The first 3 A hero page_hero = page_hero[start_bracket:]start_link = page_hero.find('<a href="')start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_info3 = page_hero[start_quote+1:end_quote]print(hero_info3)start_link = page_hero.find('<img src="', end_quote+1)start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_link3 = page_hero[start_quote+1:end_quote]print(hero_link3)end_bracket = page_hero.find('>', end_quote+1)start_bracket = page_hero.find('<', end_bracket+1)hero_name3 = page_hero[end_bracket+1:start_bracket]print(hero_name3)# The first 4 A hero page_hero = page_hero[start_bracket:]start_link = page_hero.find('<a href="')start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_info4 = page_hero[start_quote+1:end_quote]print(hero_info4)start_link = page_hero.find('<img src="', end_quote+1)start_quote = page_hero.find('"', start_link)end_quote = page_hero.find('"', start_quote+1)hero_link4 = page_hero[start_quote+1:end_quote]print(hero_link4)end_bracket = page_hero.find('>', end_quote+1)start_bracket = page_hero.find('<', end_bracket+1)hero_name4 = page_hero[end_bracket+1:start_bracket]print(hero_name4)

Output :

herodetail/196.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg Hundred Li keep the promise herodetail/193.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg armoured 

You can see , look for 4 The ideas of each hero are as follows :(1) Find the first one to show up <img src= >=>start_link;(2) Find the first one to show up "=>start_quote;(3) find start_quote+1 After that quote end_quote;(4)end_quote+1 Find the one in the back > Write it down as end_bracket;(5)end_bracket+1 find start_bracket;(6) abandon start_bracket Everything before , Then find out according to the above method .

You can see ,3 Part of the code is similar to most of it , So you can use loops to simplify the code :

# Use loops to simplify code page_hero = '''<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt=" Su lie "> Su lie </a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt=" Hundred Li xuance "> Hundred Li xuance </a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt=" Hundred Li keep the promise "> Hundred Li keep the promise </a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt=" armoured "> armoured </a></li></ul>'''for i in range(4): print(' The first %d A hero :' % (i+1)) start_link = page_hero.find('<a href="') start_quote = page_hero.find('"', start_link) end_quote = page_hero.find('"', start_quote+1) hero_info = page_hero[start_quote+1:end_quote] print(hero_info) start_link = page_hero.find('<img src="', end_quote+1) start_quote = page_hero.find('"', start_link) end_quote = page_hero.find('"', start_quote+1) hero_link = page_hero[start_quote+1:end_quote] print(hero_link) end_bracket = page_hero.find('>', end_quote+1) start_bracket = page_hero.find('<', end_bracket+1) hero_name = page_hero[end_bracket+1:start_bracket] print(hero_name) page_hero = page_hero[start_bracket:]

Output :

 The first 1 A hero :herodetail/194.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg Su Liedi 2 A hero :herodetail/195.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg A hundred Li Xuan CE di 3 A hero :herodetail/196.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg Baili Shouji 4 A hero :herodetail/193.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg armoured 

obviously , The code is much simpler .

Two 、 Function introduction and basic use

A function is a named piece of code , And independent of all other code . Functions can take any type of input parameters , And return any number and type of output results . In short , A function can Instead of a lot of code , When you need to use this code 、 Call the function directly , Instead of repeating large pieces of code , Greatly optimized the structure of the code 、 Improved the efficiency of the code Readability .

Define a function that does nothing as follows :

# An empty function that does nothingdef do_nothing(): passdo_nothing()type(do_nothing)

Output :

function

among ,do_nothing() Call function , namely Function name ().

Define a function without parameters and return values as follows :

# A function without parameters and returns valuesdef greeting(): print("Hello Python")# Call the functiona = greeting()

Output :

Hello Python

You need to print later Hello Python The place of , You don't have to use print("Hello Python") sentence , Call directly greeting() that will do .

You can also define with parameters 、 But functions without return values :

# A function with a parameter that returns nothingdef greeting(name): print("Hello %s" % name)# Call the functiongreeting('Corley')

Output :

Hello Corley

In this case, when the function is called , Parameter passed in 'Corley', Will be used inside the function , If the parameter value changes , The variables used inside the function also change synchronously , The results can also change .

But at this time :

print(a)

Output :

None

That is, the return is empty , This is because the return value is not defined inside the function . If necessary, you can define the return value inside the function , So that it can be used in the next operation .

as follows :

# A function with a parameter and return a stringdef greeting_str(name): return "Hello again " + name# Use the functions = greeting_str("Corley")print(s)

Output :

Hello again Corley

Like many programming languages ,Python Support positional parameters , The values are copied to the corresponding parameters in order . That is, you can pass multiple parameters to the function , as follows :

# A function with 3 parametersdef menu(wine, entree, dessert): return "wine:{},entree:{},dessert:{}".format(wine,entree,dessert)# Get a menumenu('chardonnay', 'chicken', 'cake')

Output :

'wine:chardonnay,entree:chicken,dessert:cake'

To avoid confusion of position parameters , Parameters can be specified by their corresponding names , You can even specify parameters in a different order than defined in a function , That is, keyword parameters . as follows :

menu(entree='beef', dessert='cake', wine='bordeaux')

Output :

'wine:bordeaux,entree:beef,dessert:cake'

obviously , At this time, parameter transmission can be realized without following the sequence .

You can even mix positional and keyword parameters ; But we need to pay attention , Before entering any keyword parameters , All position parameters must be provided .

If the function caller does not provide default values for any parameters , You can set the default value for the parameter . as follows :

# default dessert is puddingdef menu(wine, entree, dessert='pudding'): return "wine:{},entree:{},dessert:{}".format(wine,entree,dessert)# Call menu without providing dessertmenu('chardonnay', 'chicken')

Output :

'wine:chardonnay,entree:chicken,dessert:pudding'

You can see , At this time, you may not give dessert Parameter transfer can also operate normally , Because the default value has been provided when the function is defined .

Of course , You can also give dessert Parameter values , Instead of the default value, the passed value is used , as follows :

# Default value will be overwritten if caller provide a valuemenu('chardonnay', 'chicken', 'doughnut')

Output :

'wine:chardonnay,entree:chicken,dessert:doughnut'

In the function , There are scopes , That is, whether the variable is valid inside and outside the function . as follows :

x = 1def new_x(): x = 5 print(x)def old_x(): print(x)new_x()old_x()

Output :

51

obviously , In the first function x Inside the function , It's a local variable , Local variables can only be used inside the current function ; The second function uses x There is no definition inside the function , So use the function outside of x, Global variables , Global variables can be used inside functions , It can also be used outside functions ; The function defines a local variable with the same name as the global variable , Does not change the value of the global variable .

To use global variables inside functions and modify them , Need to use global Keyword to declare . as follows :

x = 1def change_x(): global x print('before changing inside,', x) x = 3 print('after changing inside,', x)print('before changing outside,', x)change_x()print('after changing outside,', x)

Output :

before changing outside, 1before changing inside, 1after changing inside, 3after changing outside, 3

You can see , At this point, after modifying the variables inside the function , The outside of the function also changes .

At this time, we can further optimize the pure text analysis case of Wang Yao :

# Use functions to implement def extract_info(current_page): start_link = current_page.find('<a href="') start_quote = current_page.find('"', start_link) end_quote = current_page.find('"', start_quote+1) hero_info = current_page[start_quote+1:end_quote] print(hero_info) start_link = current_page.find('<img src="', end_quote+1) start_quote = current_page.find('"', start_link) end_quote = current_page.find('"', start_quote+1) hero_link = current_page[start_quote+1:end_quote] print(hero_link) end_bracket = current_page.find('>', end_quote+1) start_bracket = current_page.find('<', end_bracket+1) hero_name = current_page[end_bracket+1:start_bracket] print(hero_name) return start_bracketstart_bracket = 0page_hero = '''<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt=" Su lie "> Su lie </a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt=" Hundred Li xuance "> Hundred Li xuance </a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt=" Hundred Li keep the promise "> Hundred Li keep the promise </a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt=" armoured "> armoured </a></li></ul>'''for i in range(4): print(' The first %d A hero :' % (i+1)) page_hero = page_hero[start_bracket:] start_bracket = extract_info(page_hero) 

Output :

 The first 1 A hero :herodetail/194.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg Su Liedi 2 A hero :herodetail/195.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg A hundred Li Xuan CE di 3 A hero :herodetail/196.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg Baili Shouji 4 A hero :herodetail/193.shtmlhttp://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg armoured 

obviously , Loops are used in combination with functions , Realized the function , And further simplify the code .

Besides using for loop , You can also use while loop , as follows :

# Use functions to implement def extract_info(i, current_page): start_link = current_page.find('<a href="') start_quote = current_page.find('"', start_link) end_quote = current_page.find('"', start_quote+1) hero_info = current_page[start_quote+1:end_quote] start_link = current_page.find('<img src="', end_quote+1) start_quote = current_page.find('"', start_link) end_quote = current_page.find('"', start_quote+1) hero_link = current_page[start_quote+1:end_quote] end_bracket = current_page.find('>', end_quote+1) start_bracket = current_page.find('<', end_bracket+1) hero_name = current_page[end_bracket+1:start_bracket] if hero_info.startswith('hero'): print(' The first %d A hero :' % i) print(hero_info) print(hero_link) print(hero_name) return start_bracket else: return -1start_bracket = 0i = 1page_hero = '''<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt=" Su lie "> Su lie </a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt=" Hundred Li xuance "> Hundred Li xuance </a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt=" Hundred Li keep the promise "> Hundred Li keep the promise </a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt=" armoured "> armoured </a></li></ul>'''while True: page_hero = page_hero[start_bracket:] start_bracket = extract_info(i, page_hero) i += 1 if start_bracket == -1: break

The effect is the same as before .

3、 ... and 、 Function advanced

1. Variable position parameters

In general , After defining a function with several parameters , In the call , You also need to pass the same number of parameter values to call the function properly , Otherwise, an error will be reported . But you can also see , Before calling print() Function time , The number of variables to print each time may be different , That is, the number of parameters may be variable , If you need to define a constant number of parameters , You need to use parameters *args, Also known as Variable position parameters .

as follows :

def print_args(*args): print('Positonal args:', args)print('hello', 'Corley')print('hello', 'Corley','again')print('what', 'are','you','doing')

Output :

hello Corleyhello Corley againwhat are you doing

obviously , At this time, different numbers of parameters are passed in , All functions can be called normally .

see args type , as follows :

def print_args(*args): print(type(args)) print('Positonal args:', args)print_args('hello')

Output :

<class 'tuple'>Positonal args: ('hello',)

You can see , Incoming args Types are resolved to tuples , Contains all the parameters passed ;print() Functions are defined in a similar way .

When you define a function , Passing parameters can be more flexible . as follows :

def print_args_with_required(req1, req2, *args): print('req1:', req1) print('req2:', req2) print('all other args:', args)print_args_with_required()

Error will be reported at this time :

---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-79-0f8d1d1519ce> in <module> 4 print('all other args:', args) 5 ----> 6 print_args_with_required()TypeError: print_args_with_required() missing 2 required positional arguments: 'req1' and 'req2'

Because that's how we define functions , Is said req1 and req2 They are all parameters that must be transferred , You can also decide whether to pass other parameters as needed , If so, include args in , At this point, the call does not pass the first two parameters , So it will report a mistake .

test :

def print_args_with_required(req1, req2, *args): print('req1:', req1) print('req2:', req2) print('all other args:', args)print_args_with_required(1,2)print_args_with_required(1,2, 3, 'hello')

Output :

req1: 1req2: 2all other args: ()req1: 1req2: 2all other args: (3, 'hello')

here , If there are extra parameters , The tuple is placed .

2. Variable key parameters

Previously, no parameter name was specified when additional parameters were passed in , Pass in the parameter value directly , But you can also specify parameter names , At this point is called Variable key parameters , In the form of **kwargs.

as follows :

def print_kwargs(**kwargs): print('Keyword args:', kwargs)print_kwargs(1,2)

Error will be reported at this time :

---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-81-fbc2fa215023> in <module> 2 print('Keyword args:', kwargs) 3 ----> 4 print_kwargs(1,2)TypeError: print_kwargs() takes 0 positional arguments but 2 were given

In this case, you need to specify the parameter name , as follows :

def print_kwargs(**kwargs): print('Keyword args:', kwargs)print_kwargs(fst=1,scd=2)

Output :

Keyword args: {'fst': 1, 'scd': 2}

You can see , Variable keyword parameters are parsed into dictionaries .

Variable location parameters and variable keyword parameters can be used in combination . as follows :

def print_all_args(req1, req2, *args, **kwargs): print('required args:', req1, req2) print('Positonal args:', args) print('Keyword args:', kwargs)print_all_args(1,2,3,4,s='hello')

Output :

required args: 1 2Positonal args: (3, 4)Keyword args: {'s': 'hello'}

When defining and calling functions , We need to pay attention to 3 The order of the positions of the two parameters : The required parameter is at the top , The variable position parameter takes the second place , The variable keyword parameter is at the end of .

3. Functions to define and view document strings

Functions defined in the system generally have docstring , The parameters used to describe the function 、 Usage notes, etc .

for example :

?print

After operation , It will pop up at the bottom of the page , The content is :

Docstring: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.Type: builtin_function_or_method

among , The first part is the internally defined document string .

Custom functions can also implement this function , as follows :

def odd_or_even(num): ''' Return True id num is even, or return False if num is odd ''' return num % 2 == 0?odd_or_even

In this case, the content in the pop-up box is :

Signature: odd_or_even(num)Docstring:Return True id num is even,or return False if num is oddFile: XXX\<ipython-input-85-b86074aa0e21>Type: function

You can see , Is defined in the form of three pairs of quotation marks wrapping a document string , It is equivalent to annotation , But it's also a document string .

You can also use help() Function implementation view function documentation :

help(odd_or_even)

Output :

Help on function odd_or_even in module __main__:odd_or_even(num) Return True id num is even, or return False if num is odd

Or use the __doc__ attribute , as follows :

print(odd_or_even.__doc__)

Output :

Return True id num is even,or return False if num is odd

5. Function as parameter

The function itself can also be passed as an argument to another function , To call .

as follows :

def ask(): print('Do you love Python?')def answer(): print('Yes, I do')def run_sth(func): func()run_sth(ask)run_sth(answer)

Output :

Do you love Python?Yes, I do

You can see , It can also be executed normally .

You can also pass parameters :

def bin_op(func, op1, op2): return func(op1, op2)def add(op1, op2): return op1 + op2def sub(op1, op2): return op1 - op2print('1 + 2 =', bin_op(add, 1,2))print('1 - 2 =', bin_op(sub, 1,2))

Output :

1 + 2 = 31 - 2 = -1

You can also define nested functions . as follows :

def exp_factory(n): def exp(a): return a ** n return expsqr = exp_factory(2)print(type(sqr))print(sqr(3))

Output :

<class 'function'>9

You can see , call exp_factory(2) When you return exp() function , Its interior is return a ** 2, That is to find the square of a number , So call sqr(3) when , That is to call exp(3), So back 3**2=9.

This is known as Factory function Pattern , You can produce functions with specific functions . Again :

cube = exp_factory(3)cube(3)

Output :

27

6. Decorator

Function can be used Decorator , Implement additional functions that cannot be implemented by using functions alone . In short : Decorators are functions that modify the functions of other functions , It helps make the code shorter , And more Pythonic.

for example :

def should_log(func): def func_with_log(*args, **kwargs): print('Calling:', func.__name__) return func(*args, **kwargs) return func_with_logadd_with_log = should_log(add)add_with_log(2,3)

Output :

Calling: add5

You can see , Through the transfer function to should_log() Function , Make the function have other functions , For example, printing logs ;__name__ Property is used to get the name of the function .

But it's not very convenient , In this case, it can be further simplified as follows :

@should_logdef add(op1, op2): return op1 + op2@should_logdef sub(op1, op2): return op1 * op2add(1, 2)sub(1, 2)

Output :

Calling: addCalling: sub2

In this case, the required functions are realized in a simpler way , This is the decorator , It's often applied to authorization and logging .

7. Anonymous functions -lambda expression

Previously defined functions are defined in a specific form , as follows :

def mul(op1, op2): return op1 * op2

You can see , This function passes through def Keyword definition , There's a function called mul, There are also two parameters and a return value , But actually the function is very simple , Is to find the product of two numbers and return , obviously , It is not appropriate to use this function in less places or far away from the current code . You can use Anonymous functions , A function that has no function name , Also called lambda expression , Can realize the function function function . as follows :

bin_op(lambda op1, op2:op1*op2, 2,4)

Output :

8

lambda Expressions are generally used in places where functions are not complex and are not used much .

8. exception handling

A lot of times , Because the code logic is not correct, an error will be reported , That is, throw an exception , Can be done Capture and processing , So that the program continues to run . In this case, we need to use try...except... sentence . as follows :

def div(op1, op2): try: return op1 / op2 except ZeroDivisionError: print('Division by zero')div(5, 0)

Output :

Division by zero

You can see , Now the divisor is 0, But no exception was thrown , It's execution except The statement in ; If try No exception in code block , The code block is executed normally , Otherwise execution except Code in block .

It can also be combined with finally Use . as follows :

def div(op1, op2): try: return op1 / op2 except: print('Division by zero') finally: print('finished')div(5, 0)

Output :

Division by zerofinished

At this time, no matter what is executed try still except The statement in , Will eventually be implemented finally The statement in . Exception handling can improve Program stability , Minimize the impact of exceptions on the program .

There are additional code structure exercises , If necessary , You can click add directly QQ Group Python Geek tribe 963624318 In the group folder Business data analysis from entry to entry You can download it in .

this paper First text From the blog column Data analysis , Forwarded by me to https://www.helloworld.net/p/Mne4cgaiw7Ij8, Other platforms are infringing , Clickable https://blog.csdn.net/CUFEECR/article/details/108751537 Look at the original , You can also click https://blog.csdn.net/CUFEECR Browse more quality original content .

 Preview
版权声明
本文为[CuterCorley]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/04/20210405220533504Y.html

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database