Home > Article > Backend Development > Four common mistakes to avoid when learning Python
#Python is an excellent language for beginners, but that doesn’t mean you can’t make mistakes. Especially in the early stages of learning to program, it's easy to write code that is technically correct but stylistically poor.
If you are going to learn to code, it is crucial to learn it well. Whether in academia or industry, the quality of code is important. It affects not just you, but everyone who will continue to read and use your code. Perhaps more selfishly, it can also impact your recruiting prospects.
In this article, I will discuss four common mistakes made by introductory Python programmers. Learning these pitfalls was very helpful to me in my early Python days, and I hope it will be useful to you too.
let's start.
This is a common mistake that entry-level programmers make. This is also a mistake made by less novice programmers who lack a formal programming background because they just use code as a tool. I'm looking at you, data scientists.
Conditional statements in Python are useful, but not always necessary. This is especially true when the condition you're checking already contains a Boolean value (true or false).
Let me illustrate with a simple example. Suppose we want to write code to determine whether a data set has been cleaned. Luckily for us, the codebase includes a convenience variable called is_data_clean that keeps track of this. All we need to do is check it and return the correct value.
As a first try, we might write something like this:
def a_function(): if is_data_clean == True: return True else: return False
This already works, but it doesn't have to be this complicated. Do you see the problem? look carefully.
The variable is_data_clean is already a boolean; therefore, it already contains the value you need to return! The code checks if it is True and returns True, if it is not True (meaning it is False) then the code returns False. It's just a bunch of unnecessary checks.
We can reduce the code in the function to one line:
def a_function(): return is_data_clean
Much better.
Python has more built-in functionality than most people realize. There are just too many people who still use loops to manually calculate sums.
If we have a list of numbers in Python, we should never calculate the sum like this:
total = 0 for num in numbers_list: total += num
Please use the built-in seek instead And function:
total
Need a minimum or maximum value? There is no prohibition in the universe that you should write code like this:
import math minimum = math.inf # 从最高可能值开始 for number in numbers_list: if number < minimum: minimum = number
This is not an introductory computer science principles course; this is the real world. Stop reinventing the wheel and use the built-in min and max functions:
minimum = min(numbers_list) maximum
For a complete list of built-in functions, see the Python documentation
Bonus: Built-in functions that are not technically built-in .
Some features are hard to find, but that doesn't mean you shouldn't find them.
For example, if we needed the average of a column of numbers (you may feel this is a recurring theme), we could use the first code snippet below, but we should use the Two:
# 片段 1:不要这样做! total = 0 for num in numbers_list: total += num avg = total / len(numbers_list) # 片段 2:这样做! import numpy as np avg = np.mean(numbers_list)
Usually, Python provides useful functions in modules. Locating the modules we need and importing the functions may require some extra work, but it's well worth it.
Remember — Python is all about simplicity and readability. Built-in functions are your friends. Unlike your human friends, they never disappoint.
在我教授的一门 Python 入门课程中,学生的第一个项目是编写一个简单的决策算法。 这主要是一个条件练习,要求学生定义一个问题和相关的评分系统,以确定某人有资格回答这个问题的可能性。
例如,有人可能会问,“我应该成为一名数据科学家吗?” 然后,该算法可能包含以下问题,所有这些问题都会根据答案从最终输出分数中增加或减少:
等等。
在编写算法的过程中,许多学生意识到在某些情况下,他们根本不想对总分做任何事情。 例如,他们可能会决定,如果有人愿意学习 Python,那么他们的总分会增加 10 分,但如果他们不愿意,则分数保持不变。
大多数学生使用以下代码实现它:
# willing_to_lean 是一些基于用户输入的预定义变量 if willing_to_learn: score += 10 else: score += 0
这是什么都不做的经典案例。 让我们分解一下 Python 在看到代码行 score += 0 时必须执行的所有操作:
所有这些代码什么都不做。
当然,这对计算机来说不是很大的工作量,也不会对代码的效率产生任何有意义的影响。 也就是说,它毫无意义,而且有些不干净,这是优秀 Python 代码所不具备的特征。
更好的解决方案是使用 Python 的 pass 关键字,它实际上告诉 Python 什么都不做,继续前进。 它填充了一行不需要的代码,但如果完全留空就会出错。 我们甚至可以添加一点评论以提供进一步的清晰度:
if willing_to_learn: score += 10 else: pass # 保持分数不变
更干净、更清晰、更 Pythonic。
条件语句可以说是标准编程中最强大和一致的结构之一。 第一次学习它时,很容易忽略一个重要的微妙之处。
当我们要检查两个或多个条件时,就会出现这种情况。 例如,假设我们正在审查一项调查,以获取以下三种形式之一的回答:“Yes”、“No”或“Maybe”。
早期的 Python 程序员通常使用以下两种方式之一对此进行编码:
# 可能 1 if response == "Yes": # do something if response == "No": # do something if response == "Maybe": # do something # 可能 2 if response == "Yes": # do something elif response == "No": # do something else: # do something
在这种情况下,这两个代码片段实际上是相同的。 它们的行为方式相同,理解起来并不特别混乱,并且它们实现了预期的目标。 当人们错误地认为上面的两个结构总是等价时,问题就出现了。
这是错误的。 上面的第二个代码片段是由多个部分组成的单个条件表达式,而第一个代码片段由三个独立的条件表达式组成,尽管它们看起来是相互关联的。
为什么这很重要? 因为每当 Python 看到一个全新的 if 关键字(即一个新的条件表达式开始)时,它就会检查关联的条件。 另一方面,如果当前条件表达式中的先前条件不满足,Python 只会输入 elif 或 else 条件。
让我们看一个例子,看看为什么这很重要。 假设我们需要编写代码,根据学生在某项作业中的分数给他们打分。 我们在Python 文件中写入以下代码:
score = 76 print("SNIPPET 1") print() if score < 100: print('A') elif score < 90: print('B') elif score < 80: print('C') elif score < 70: print('D') else: print('F') print() print("SNIPPET 2") print() if score < 100: print('A') if score < 90: print('B') if score < 80: print('C') if score < 70: print('D') if score < 60: print('F')
运行此代码输出以下内容:
SNIPPET 1 A SNIPPET 2 A B C
你看得到差别吗? 在第二种情况下,我们得到了意想不到的输出。 为什么? 因为 Python 将每个 if 语句作为一个新的条件来读取,所以如果一个分数恰好小于多个数字检查,则会为所有这些打印出相应的字母等级。
现在,有多种方法可以使用多个 if 语句; 例如,我们可以让条件检查范围而不仅仅是上限。 这个例子的重点不是争论一个例子优于另一个例子(尽管为了清楚起见,我个人倾向于使用 elif 和 else),而只是为了说明它们是不一样的。
确保你明白这一点。
这是您的 Python 初学者备忘单:
你决定学习 Python 真是太好了——我向你保证,这门语言会对你很好。
The above is the detailed content of Four common mistakes to avoid when learning Python. For more information, please follow other related articles on the PHP Chinese website!