Techno Blender
Digitally Yours.

4 Common Python Mistakes You Should Avoid as a Beginner | by Murtaza Ali | Jan, 2023

0 41


Photo by David Pupaza on Unsplash

Python is an excellent language for beginners, but that doesn’t mean there are no mistakes to be made. Especially during the early stages of learning to program, it’s easy to write code that is technically correct, but stylistically poor.

If you’re going to learn to code, it’s crucial that you learn to do it well. Be it in academia or industry, the quality of your code matters. It affects not only you, but each and every person who will go on to read and work with your code. Perhaps more selfishly, it also affects your hiring prospects.

In this article, I’ll discuss four common mistakes made by introductory Python programmers. Learning these traps in my early Python days was extremely helpful for me, and I hope it can be for you as well.

Let’s get into it.

The Good Old Boolean Conditional

This is a common mistake made by introductory programmers. It’s also a mistake made by not-so-introductory programmers who nevertheless lack a formal background in programming because they simply use code as a tool. I’m looking at you, data scientists.

Conditional statements in Python are useful, but they aren’t always necessary. This is particularly true in cases when the condition you’re checking already contains a Boolean (True or False) value.

Let me illustrate with a simple example. Say wewant to write code to determine if a data set has already been cleaned. Lucky for us, the code base contains a convenient variable called is_data_clean which keeps track of this. All we need to do is check it and return the correct value.

As a first attempt, we might write something like the following:

def a_function():
if is_data_clean == True:
return True
else:
return False

This works well enough, but it’s needlessly complex. Do you see the problem? Look carefully.

The variable is_data_clean is already a Boolean; therefore, it already contains the very value you need to return! The code checks if it is True, only to then return True, and if it isn’t True (meaning it is False), the code returns False. It’s just a whole bunch of unnecessary checks.

We can simplify the code in the function to one line:

def a_function():
return is_data_clean

Much better.

The manual sum, mean, or other built-in operation

Python has more built-in functionality than most people realize. The number of people still using a loop to manually calculate a sum is too damn high.

If we have a list of numbers in Python, we absolutely should not be calculating the sum like this:

total = 0
for num in numbers_list:
total += num

Use the built-in sum function instead:

total = sum(numbers_list)

Need a minimum or maximum? The universe forbid you write something like this:

import math
minimum = math.inf # start at highest possible value
for number in numbers_list:
if number < minimum:
minimum = number

This isn’t an introductory computer science principles class; it’s the real world. Stop reinventing the wheel and use the built-in min and max functions:

minimum = min(numbers_list)
maximum = max(numbers_list)

For a full list of built-in functions, see the Python documentation [1].

Bonus: Built-in functions that aren’t technically built in.

Some functions are harder to find, but that doesn’t mean you shouldn’t find them.

For instance, if we need the mean of a list of numbers (you might sense a recurring theme here), we could use the first code snippet below, but we should use the second:

# Snippet 1: Don't do this!
total = 0
for num in numbers_list:
total += num
avg = total / len(numbers_list)

# Snippet 2: Do this!
import numpy as np
avg = np.mean(numbers_list)

Oftentimes, Python offers useful functions that are within modules. It might be a bit of extra work to locate the module we need and import the function, but it’s well worth the resulting code.

Remember — Python is all about simplicity and readability. Built-in functions are your friends. And unlike your human friends, they’ll never disappoint.

Doing something to do nothing

In one of the introductory Python classes I teach, the students’ first project is to write a simple decision-making algorithm. It’s primarily an exercise in conditionals, requiring the students to define a question and associated scoring system to determine the likelihood that someone qualifies for the question.

For example, one might ask, “Should I become a data scientist?” Then, the algorithm could consist of the following questions, all of which either add or subtract from the eventual output score, depending on the answer:

  • Am I interested in using data to gain insights about the world?
  • Am I willing to learn Python?
  • Do I enjoy working with multidisciplinary teams?

And so on.

In the midst of writing their algorithm, many students realize that in certain cases, they simply want to do nothing to the overall score. For example, they might decide that if someone is willing to learn Python, that adds 10 points to their overall score, but if they are unwilling, it simply leaves the score unchanged.

Most students implement this with the following code:

# willing_to_lean is some predefined variable based on user input
if willing_to_learn:
score += 10
else:
score += 0

This is a classic case of doing something to do nothing. Let’s break down everything that Python has to do when it sees the line of code score += 0:

  • It needs to look up the value of the variable score.
  • It needs to add 0 to this value. This requires calling the addition function, passing in two arguments (the current value and 0), and computing the output.
  • Reassigning the score variable to the new value (which, clearly, is the same).

All of this work to do … nothing.

Sure, it’s not a huge amount of work for the computer, and it won’t make any meaningful difference to your code’s efficiency. That said, it is pointless and somewhat unclean, which is uncharacteristic of excellent Python code.

A better solution is to use Python’s pass keyword, which literally tells Python to do nothing and just move on. It fills in a line of code which doesn’t need to be there, but which would error if left completely empty. We can even add a little comment to provide further clarity:

if willing_to_learn:
score += 10
else:
pass # Leave score unchanged

Cleaner, clearer, more Pythonic.

The single conditional gone wild

The conditional statement is arguably one of the more powerful and consistent constructs in standard programming. When learning it for the first time, it is easy to overlook an important subtlety.

This subtlety arises when we want to check for two or more conditions. For example, say we are reviewing a survey for responses that take one of three forms: “Yes,” “No,” or “Maybe.”

Early Python programmers often code this in one of two ways:

# Possibility 1
if response == "Yes":
# do something
if response == "No":
# do something
if response == "Maybe":
# do something

# Possibility 2
if response == "Yes":
# do something
elif response == "No":
# do something
else:
# do something

In this context, both of these code snippets are effectively the same. They behave in the same way, they aren’t particularly confusing to understand, and they accomplish the desired goal. The issue arises when people mistakenly believe that the two structures above are always equivalent.

This is false. The second code snippet above is a single conditional expression made of multiple parts, whereas the first code snippet consists of three, separate conditional expressions, despite the fact that they appear interconnected.

Why is this important? Because whenever Python sees a brand new if keyword (i.e., a new conditional expression starting), it will check the associated condition. On the other hand, Python will only ever enter an elif or else condition if no previous conditions in the current conditional expression have been satisfied.

Let’s look at an example to see why this matters. Say we need to write code that assigns students a letter grade based on their numerical score on some assignment. We write the following code in out Python file:

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')

Running this code outputs the following:

SNIPPET 1

A

SNIPPET 2

A
B
C

Do you see the difference? In the second case, we get an unexpected output. Why? Because Python reads every if statement as a brand new conditional, and so if a score happens to be less than multiple number checks, the corresponding letter grade gets printed out for all of them.

Now, there are ways to make this work with multiple if statements; for instance, we could make it so the condition checks for a range rather than just an upper limit. The point of this example is not to argue for the merits of one example over the other (although I would personally lean toward making use of elif and else for clarity), but simply to illustrate that they are not the same.

Be sure you understand that.

Final Thoughts and Recap

Here’s your Python beginner cheat sheet:

  1. Don’t make unnecessary conditionals for Booleans when you can simply return the Boolean value directly.
  2. Built-in functions are your best friends.
  3. If you need to tell Python to do nothing, use the pass keyword.
  4. Make sure you structure conditional expressions correctly, understanding the meaning of the if , elif , and else keywords.

It’s excellent that you’ve decided to learn Python — I assure you that the language shall treat you well.

Just be sure to return the favor.


Photo by David Pupaza on Unsplash

Python is an excellent language for beginners, but that doesn’t mean there are no mistakes to be made. Especially during the early stages of learning to program, it’s easy to write code that is technically correct, but stylistically poor.

If you’re going to learn to code, it’s crucial that you learn to do it well. Be it in academia or industry, the quality of your code matters. It affects not only you, but each and every person who will go on to read and work with your code. Perhaps more selfishly, it also affects your hiring prospects.

In this article, I’ll discuss four common mistakes made by introductory Python programmers. Learning these traps in my early Python days was extremely helpful for me, and I hope it can be for you as well.

Let’s get into it.

The Good Old Boolean Conditional

This is a common mistake made by introductory programmers. It’s also a mistake made by not-so-introductory programmers who nevertheless lack a formal background in programming because they simply use code as a tool. I’m looking at you, data scientists.

Conditional statements in Python are useful, but they aren’t always necessary. This is particularly true in cases when the condition you’re checking already contains a Boolean (True or False) value.

Let me illustrate with a simple example. Say wewant to write code to determine if a data set has already been cleaned. Lucky for us, the code base contains a convenient variable called is_data_clean which keeps track of this. All we need to do is check it and return the correct value.

As a first attempt, we might write something like the following:

def a_function():
if is_data_clean == True:
return True
else:
return False

This works well enough, but it’s needlessly complex. Do you see the problem? Look carefully.

The variable is_data_clean is already a Boolean; therefore, it already contains the very value you need to return! The code checks if it is True, only to then return True, and if it isn’t True (meaning it is False), the code returns False. It’s just a whole bunch of unnecessary checks.

We can simplify the code in the function to one line:

def a_function():
return is_data_clean

Much better.

The manual sum, mean, or other built-in operation

Python has more built-in functionality than most people realize. The number of people still using a loop to manually calculate a sum is too damn high.

If we have a list of numbers in Python, we absolutely should not be calculating the sum like this:

total = 0
for num in numbers_list:
total += num

Use the built-in sum function instead:

total = sum(numbers_list)

Need a minimum or maximum? The universe forbid you write something like this:

import math
minimum = math.inf # start at highest possible value
for number in numbers_list:
if number < minimum:
minimum = number

This isn’t an introductory computer science principles class; it’s the real world. Stop reinventing the wheel and use the built-in min and max functions:

minimum = min(numbers_list)
maximum = max(numbers_list)

For a full list of built-in functions, see the Python documentation [1].

Bonus: Built-in functions that aren’t technically built in.

Some functions are harder to find, but that doesn’t mean you shouldn’t find them.

For instance, if we need the mean of a list of numbers (you might sense a recurring theme here), we could use the first code snippet below, but we should use the second:

# Snippet 1: Don't do this!
total = 0
for num in numbers_list:
total += num
avg = total / len(numbers_list)

# Snippet 2: Do this!
import numpy as np
avg = np.mean(numbers_list)

Oftentimes, Python offers useful functions that are within modules. It might be a bit of extra work to locate the module we need and import the function, but it’s well worth the resulting code.

Remember — Python is all about simplicity and readability. Built-in functions are your friends. And unlike your human friends, they’ll never disappoint.

Doing something to do nothing

In one of the introductory Python classes I teach, the students’ first project is to write a simple decision-making algorithm. It’s primarily an exercise in conditionals, requiring the students to define a question and associated scoring system to determine the likelihood that someone qualifies for the question.

For example, one might ask, “Should I become a data scientist?” Then, the algorithm could consist of the following questions, all of which either add or subtract from the eventual output score, depending on the answer:

  • Am I interested in using data to gain insights about the world?
  • Am I willing to learn Python?
  • Do I enjoy working with multidisciplinary teams?

And so on.

In the midst of writing their algorithm, many students realize that in certain cases, they simply want to do nothing to the overall score. For example, they might decide that if someone is willing to learn Python, that adds 10 points to their overall score, but if they are unwilling, it simply leaves the score unchanged.

Most students implement this with the following code:

# willing_to_lean is some predefined variable based on user input
if willing_to_learn:
score += 10
else:
score += 0

This is a classic case of doing something to do nothing. Let’s break down everything that Python has to do when it sees the line of code score += 0:

  • It needs to look up the value of the variable score.
  • It needs to add 0 to this value. This requires calling the addition function, passing in two arguments (the current value and 0), and computing the output.
  • Reassigning the score variable to the new value (which, clearly, is the same).

All of this work to do … nothing.

Sure, it’s not a huge amount of work for the computer, and it won’t make any meaningful difference to your code’s efficiency. That said, it is pointless and somewhat unclean, which is uncharacteristic of excellent Python code.

A better solution is to use Python’s pass keyword, which literally tells Python to do nothing and just move on. It fills in a line of code which doesn’t need to be there, but which would error if left completely empty. We can even add a little comment to provide further clarity:

if willing_to_learn:
score += 10
else:
pass # Leave score unchanged

Cleaner, clearer, more Pythonic.

The single conditional gone wild

The conditional statement is arguably one of the more powerful and consistent constructs in standard programming. When learning it for the first time, it is easy to overlook an important subtlety.

This subtlety arises when we want to check for two or more conditions. For example, say we are reviewing a survey for responses that take one of three forms: “Yes,” “No,” or “Maybe.”

Early Python programmers often code this in one of two ways:

# Possibility 1
if response == "Yes":
# do something
if response == "No":
# do something
if response == "Maybe":
# do something

# Possibility 2
if response == "Yes":
# do something
elif response == "No":
# do something
else:
# do something

In this context, both of these code snippets are effectively the same. They behave in the same way, they aren’t particularly confusing to understand, and they accomplish the desired goal. The issue arises when people mistakenly believe that the two structures above are always equivalent.

This is false. The second code snippet above is a single conditional expression made of multiple parts, whereas the first code snippet consists of three, separate conditional expressions, despite the fact that they appear interconnected.

Why is this important? Because whenever Python sees a brand new if keyword (i.e., a new conditional expression starting), it will check the associated condition. On the other hand, Python will only ever enter an elif or else condition if no previous conditions in the current conditional expression have been satisfied.

Let’s look at an example to see why this matters. Say we need to write code that assigns students a letter grade based on their numerical score on some assignment. We write the following code in out Python file:

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')

Running this code outputs the following:

SNIPPET 1

A

SNIPPET 2

A
B
C

Do you see the difference? In the second case, we get an unexpected output. Why? Because Python reads every if statement as a brand new conditional, and so if a score happens to be less than multiple number checks, the corresponding letter grade gets printed out for all of them.

Now, there are ways to make this work with multiple if statements; for instance, we could make it so the condition checks for a range rather than just an upper limit. The point of this example is not to argue for the merits of one example over the other (although I would personally lean toward making use of elif and else for clarity), but simply to illustrate that they are not the same.

Be sure you understand that.

Final Thoughts and Recap

Here’s your Python beginner cheat sheet:

  1. Don’t make unnecessary conditionals for Booleans when you can simply return the Boolean value directly.
  2. Built-in functions are your best friends.
  3. If you need to tell Python to do nothing, use the pass keyword.
  4. Make sure you structure conditional expressions correctly, understanding the meaning of the if , elif , and else keywords.

It’s excellent that you’ve decided to learn Python — I assure you that the language shall treat you well.

Just be sure to return the favor.

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment