程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

10 Python mistakes that beginners must make

編輯:Python

Preface

When we start to learn Python when , We will develop some bad coding habits , What's more terrible is that we don't even know .

In the process of learning to become , Probably have such an experience : The code can only do the job once , However, an error or failure will be reported later , It's annoying ,

Or when you stumble upon a built-in function that makes your job easier , Suddenly the light came out .

Most of us still use a lot Python Bad habits , These habits are learned by us python In the early stage of , Today you can explain it in the following chapters

Kill them .

1. Use import *

When we try to save time , We temporarily load the package , Use :

1.from xyz import *

It's not a good habit , For many reasons . Just a few examples :

1. inefficiency . If the module has a large number of objects , It takes a long time to wait , Until all object Are imported .

2. May cause conflicts between variable names . When you use * when , We don't know which objects to import and their names .

How to deal with this problem ? Import specific objects you intend to use

1.# Using import *
python Exchange of learning Q Group :906715085###
3.from math import *
5.print(floor(2.4))
7.print(ceil(2.4))
9.print(pi)
11.# Good
13.import math
15.from math import pi
17.print(math.floor(2.4))
19.print(math.ceil(2.4))
21.print(pi)

2. Try/Except: Not in "except " Clause

I have neglected this problem for a long time ~

stay Pycharm Write in python When , Always remind me of mistakes , Um. , You'll see , It's those ugly underscores . I shouldn't use bare except.PEP 8 The guide does not

Not recommended bare except.

bare except The problem is that it captures SystemExit and KeyboardInterrupt abnormal , So it can't be used Control-C To interrupt the program .

Next time you use try/except when , stay except An error will be reported in the clause .

1.# Try - except
3.# Wrong writing 
5.try:
7.driver.find_element(...)
9.except:
11.print("Which exception?")
13.# Advocate writing 
15.try:
17.driver.find_element(...)
19.except NoSuchElementException:
21.print("It's giving NoSuchElementException")
23.except ElementClickInterceptedException:
25.print("It's giving ElementClickInterceptedException")

3. Don't use Numpy Carry out mathematical calculation

We are encouraged to actively use mature packages , Writing this way can make Python More concise 、 More efficient .

One of the most suitable packages for mathematical computation is Numpy.Numpy Can help you compare for Loops solve math faster .

Suppose we have a random_scores Array , We want to get the average score of those who fail the exam ( fraction <60). Let's try for Cycle to solve this problem .

1.import numpy as np
3.random_scores = np.random.randint(1, 100, size=10000001)
5.# bad (solving problem with a for loop)
7.count_failed = 0
9.sum_failed = 0
11.for score in random_scores:
13. if score < 70:
15. sum_failed += score
17. count_failed += 1
19.print(sum_failed/count_failed)

Now let's use Numpy To solve this problem .

1.# Good (solving problem using vector operations)
3.mean_failed = (random_scores[random_scores < 70]).mean()
5.print(mean_failed)

If you run both at the same time , You'll find that Numpy faster . Why? ? because Numpy Vectorize our operations .

  1. Do not close previously opened files

As we all know, the good practice is , We use it Python Every open file must be closed .

That's why we use... Every time we process a file open, write/read, close. This is good , But if write/read Method throws an exception , The file will not be closed .

To avoid this problem , We have to use with sentence . such , Even if there are exceptions , It will also close the file .

1.# Bad
3.f = open('dataset.txt', 'w')
5.f.write('new_data')
7.f.close()
9.# Good
11.with open('dataset.txt', 'w') as f:
13.f.write('new_data')

5. Non compliance PEP8

PEP8 Is a copy of every study Python All people should read the document . It provides information on how to write Python Code guidelines and best practices ( Some of the suggestions in this article

since PEP8)

For those who have just come into contact with Python For people who , This rule may worry them , But don't worry , some PEP8 The rules are incorporated into IDE in ( This is me

Like to know bare except Regular ).

Suppose you are using Pycharm. If you write code that doesn't follow PEP8 Principle of , You will see the ugly underline in the following picture .

If you hover over the underline , You will see tips on how to fix them .

In my case , I just need to be in , and : Add a space after .

1.# Good
3.my_list = [1, 2, 3, 4, 5]
5.my_dict = {
'key1': 'value1', 'key2': 'value2'}
7.my_name = "Frank"

I also put my variables x The name of is changed to my_name. This is not Pycharm Suggested , but PEP8 It is recommended to use variable names that are easy to understand .

6. The dictionary is not used correctly .key and .values Method

I think most people know that when using dictionaries , .keys and .values The role of methods .

If you don't know , Let's see .

1.dict_countries = {
'USA': 329.5, 'UK': 67.2, 'Canada':
2.>>>dict_countries.keys()
3.dict_keys(['USA', 'UK', 'Canada'])
4.>>>dict_countries.values()
5.dict_values([329.5, 67.2, 38])

The problem here , We don't understand and use them correctly .

Suppose we want to cycle through dictionary And get keys. You may use .keys Method , But did you know that you can get keys by looping through the dictionary ? In this way

Under the circumstances , Use .keys Will be unnecessary .

1.# Not using .keys() properly
3.# Bad
5.for key in dict_countries.keys():
7. print(key)
9.# Good
11.for key in dict_countries:
13. print(key)

in addition , We may come up with some workarounds to get the value of the dictionary , But this can be used .items() The method is easy to get .

1.# Not using .items()
3.# Bad
5.for key in dict_countries:
7. print(dict_countries[key])
9.# Good
11.for key, value in dict_countries.items():
13. print(key)
15. print(value)

7. Never use comprehensions(

When you want to create a new sequence based on an already defined sequence ( list 、 Dictionary, etc ) when ,comprehension Provides a shorter Syntax .

For example, we want to put our countries All elements in the list are lowercase .

Although you can use one for Loop to do this , But you can simplify things with a list understanding .

Understanding is very useful , But don't overuse them ! remember Python Zen of .“ Simplicity is better than complexity ”.

1.# Bad
3.countries = ['USA', 'UK', 'Canada']
5.lower_case = []
7.for country in countries:
9. lower_case.append(country.lower())
11.# Good (but don't overuse it!)
13.lower_case = [country.lower() for country in countries]

8. Use range(len())

One of the first functions we learn as beginners is range and len, So no wonder most people write when they cycle through a list range(len()) Bad habits .

Suppose we have a countries, populations list . If we want to traverse both lists at the same time , You may use range(len()).

1.# Using range(len())
3.countries = ['USA', 'UK', 'Canada']
5.populations = [329.5, 67.2, 38]
7.# Bad
9.for i in range(len(countries)):
11. country = countries[i]
13. population = populations[i]
15. print(f'{
country} has a population of {
population} million people')

Although this can complete the work , But you can use enumerate To simplify things ( Or better yet , Use zip Function to pair elements in two lists )

1.# OK
3.for i, country in enumerate(countries):
5. population = populations[i]
7. print(f'{
country} has a population of {
population} million people')
9.# Much Better
11.for country, population in zip(countries, populations):
13. print(f'{
country} has a population of {
population} million people')
  1. Use + Operator

We are Python One of the first things to learn in may be how to use + Operators connect strings .

This is Python A useful but inefficient method of concatenating strings in . Besides , It's not that nice – The more strings you need to connect , You used + The more .

You can use f-string Instead of this operator .

1.# Formatting with + operator
3.# Bad
5.name = input("Introduce Name: ")
7.print("Good Morning, " + name + "!")
9.# Good
11.name = input("Introduce Name: ")
13.print(f'Good Morning, {
name}')

string The biggest characteristic is , It's not just useful for connecting , And there are different applications .

10. Use the default variable value

If you put a variable value ( Such as list) As the default parameter of a function , You will see some unexpected results .

1.# Bad
2.def my_function(i, my_list=[]):
3. my_list.append(i)
4. return my_list
5.>>> my_function(1)
6.[1]
7.>>> my_function(2)
8.[1, 2]
9.>>> my_function(3)
10.[1, 2, 3]

In the code above , Every time we call my_function Function time , list my_list Will keep saving the previously called values ( Probably we want to call the function every time

Start an empty list )

To avoid this behavior , We should take this my_list Parameter set to None, And add the following if Clause .

1.# Good
2.def my_function(i, my_list=None):
3. if my_list is None:
4. my_list = []
5. my_list.append(i)
6. return my_list
7.>>> my_function(1)
8.[1]
9.>>> my_function(2)
10.[2]
11.>>> my_function(3)
12.[3]

Last
This is the end of today's article , If you like it, remember to like it , More questions can be commented on , You will reply after reading !!!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved