In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What are the five bad habits when writing Python, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Note: the sample code is written in Python 3.6environment
1 use the list as the default parameter of the function
Look at the following example
Def func (a, b = []): b.append (a) print (fancia: {a}') print (fimb: {b}') func (1) func (2)
Normally, the result we expect should be like this.
A: 1 b: [1] a: 2 b: [2]
But when we execute the code, we only get this result.
A: 1 b: [1] a: 2 b: [1, 2]
Not as expected. Why? Because the Python list is a mutable object, and the function passing parameters are passed references, element 1 is already in b before the second call to the func method, and b finally has two elements 1 and 2 after the call.
In the example, the func method is relatively simple, and when you find a problem, you can find the root cause by simply looking at it. However, if you are in a more complex method, you may carelessly ignore this point and encounter some inexplicable problems.
So, when we want to set default parameters for a function, don't use mutable objects.
If the above code is changed to this, it will OK.
Def func (a, b=None): if b is None: B = [] b.append (a) print (fancia: {a}') print (fimb: {b}')
Get the expected results after implementation
A: 1 b: [1] a: 2 b: [2]
2 file operation
Many partners who just come into contact with Python can easily write similar code when doing file operations.
File = open ('file_name') try: for line in file: print (line) finally: file.close ()
This is no problem, but we do not need to maintain the file resources manually, just leave operations such as shutting down to the context manager.
With open ('file_name') as file: for line in file: print (line)
It doesn't look much refreshing.
3 catch all exceptions
Try: pass # do something except Exception as e: print (f'Exception {e}')
As above, sometimes it is easy to catch Exception exceptions in order to complete the function quickly. This may catch exceptions such as keyboard break (KeyboardInterrupt) (CTRL + C) or assertion error (AsstionError). Catching uncertain exceptions can sometimes cause inexplicable problems with our programs, and we should avoid doing so.
The accurate way is to catch specific exceptions such as ValueError, AttributeError, TypeError, etc. according to the context, and then do appropriate error handling, such as printing logs, and so on.
4 ignore the for...else syntax of Python
In development, we can easily encounter similar requirements, in a list, to determine whether a particular element exists. For example, the following code determines whether an odd number exists in the list
Numbers = [1,2,3,4,5] is_odd_exist = False for n in numbers: if n% 2 = = 1: is_odd_exist = True break if is_odd_exist: print ('Odd exist') else: print (' Odd not exist')
Here, we use an identity is_odd_exist, which defaults to False. When an odd number is found, set it to True and jump out of the loop. It's okay to write this way, but we can do it another way.
Numbers = [1,2,3,4,5] for n in numbers: if n% 2 = = 1: print ('Odd exist') break else: print (' Odd not exist')
Let's first introduce the for...else syntax of Python. When the for loop ends normally (that is, it does not end by jumping out of break), the statements in else are executed.
Here, we use a different way than other languages such as C, PHP, etc., to achieve the same function, it seems that the code is also a lot more concise.
5 use the key to traverse the dictionary
For beginners of Python, it may be easy to write such code.
Member = {'name':' xiaoming', 'age': 18,' mobile': '18312341234'} for key in member: print (f' {key}: {member [key]}')
Again, this is fine, but it doesn't look intuitive. When you traverse the dictionary, you can actually take out the key information directly, like this.
Member = {'name':' xiaoming', 'age': 18,' mobile': '18312341234'} for key, val in member.items (): print (f' {key}: {val}')
In that case, it seems to be clearer.
Some of the points mentioned above have their own certain prejudices and do not require everyone to accept them. Just choose a reasonable use.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.