Python

9 Python Mistakes only Beginners Make

What will we cover?

To get better at Python programming it is good to explore what common mistakes beginners do. This will help you avoid the same pitfalls and understand why you shouldn’t do them.

#1 Use general imports

A common mistake beginners do are importing with the wildcard (*).

from module import *

First of all, this is bad practice and can make your program slow, as you import modules you don’t need.

Also, this can import shadows variables names (the same name from different sources) and make it difficult to know what variable you are referring to.

Instead you should import specific object or whole modules you need.

You should do the following if the module name is short.

import module

This will give you access to all the sub-modules with syntax like: module.submodule.

If the module name is long, then you should do as follows.

import longmodulename as lmn

This gives access to the module with lmn.

If you only need one (or a few, but not too many) element from a module then the following.

from module import xx

The above 3 ways to do it, makes the code easy to read and understand.

#2 try/except Without Specific Exception

It is common for beginners to have a broad except Exception, as it is easy.

Example could be like this.

try:
    # do stuff
except:
    print('Some stuff went wrong!')

First of all, it does not follow the PEP8 standard. You should always try to follow PEP8, as it makes your code easier to read, maintain, and understand for others and yourself later when you need to modify, extend, or debug your code.

Also, it catches all exceptions, like SystemExit and Control-C, which can make it difficult to terminate your program.

What you should do is to catch specific exceptions.


try:
   # do your awesome stuff
except ValueException as exec:
   # Handle your exception
except NameError as exec:
   # Handle this exception here

Notice, you can have as many catchers (except) as you want for any exception type you need to handle.

#3 Not closing file

This is typical for beginners not to handle file opening proper.

f = open('file.txt', 'w')
f.write('some stuff')

Most Python interpreters close the file at the end of the program. But others don’t.

Even thought the Python interpreter closes it for you at the end, it takes up unnecessary resources from the underlying operating system, to keep a file pointer open after you needed. It can keep buffers of data that are needed to be written to storage. This can have undesired consequences if the program terminates unexpectedly.

This is especially a problem if your program is a service running and can also make the operating system run out of file pointers. It is bad practice not to close them after use.

The best practice is to use the with-statement.

with open('file.txt', 'w') as f:
    f.write('some stuff')
# Here the file pointer is closed.

This closes the file pointer after the with-statement.

#4 Not following PEP8 standard

We already talked about it, let’s talk about it again. You should always try to follow the PEP8 standard.

The reasons are clear.

  • It makes your code easy to understand for others – and yourself.

But what to do if you don’t know the PEP8 standard?

Well, I don’t know it by heart either, but there are checkers that can do that for you.

Install pep8 and let it check it for you and tell you what to correct.

pip install pep8

To check a python source file simply run and follow instructions of what to do.

pep8 python_file.py

#5 Dictionary Iteration with Keys

Actually, many beginners don’t know that you can iterate dictionaries in Python. But then they realize you can get all the keys in them.

capitals = {'Denmark': 'Copenhagen', 'Sweden': 'Stockholm', 'Norway': 'Oslo'}

for key in capitals.keys():
    print(key, capitals[key])

But if you want to get the key and values pairs you should do as follows.

for key, value in capitals.items():
    print(key, value)

#6 Not using List Comprehension

If you don’t know list comprehensions, then you often fall prey for making loops that make up lines of code not needed.

A simple example is converting a list of strings to a list of the same strings in lowercase.

my_list = ['UPPER', 'CASE', 'STUFF']

lower_case = []
for item in my_list:
    lower_case.append(item.lower())

This makes a simple transformation of a list quite difficult to read.

Using List Comprehension makes it easier.

lower_case = [item.lower() for item in my_list]

If you don’t know List Comprehension or want to learn more tricks with them, check out this the following post.

#7 Using range(len(…))

I have done this myself as a beginner. I simply didn’t know the awesome built-in functions in Python.

Say, you want to iterate over two lists simultaneously and process pairs of elements from each list. Then you might end up with the following code.

ist_0 = [1, 2, 3]
list_1 = [4, 5, 6]

for i in range(len(list_0)):
    print(list_0[i], (list_1[i])

This is bad practice and assumes that the length of the lists are the same.

The correct way to do this is to use the built-in function zip.

for i1, i2 in zip(list_0, list_1):
    print(i1, i2)

This also handles if one list is longer than the other.

If you want to learn more about the built-in functions in Python read the following guide.

#8 Use + to format strings

Most Python beginners get exited about how easy it is to concatenate strings in Python using the addition operator, that they end up using it for everything, like formatting strings.

name = "Rune"
my_str = "Hello " + name
print(my_str)

This is actually inefficient as it generates a new string for each addition. Also, it just looks bad.

What you should use is formatted strings.

my_str = f'Hello {name}'
print(my_str)

If you don’t know formatted strings, then you should read this guide.

#9 Using Non-explicit Variable Names

Here your PEP8 checker will catch you – but this is one of them that happens all the time. You create a variable with a single character.

x = 'my identifier'

While you code, it is the easiest choice. Especially, if the variable is just used in a small context.

But it makes your code difficult to understand and hard to debug.

Get those bad practices out of your system and give the variable meaningful names.

target_id = 'my identifier'

Want to learn more?

If this is something you like and you want to get started with Python, then check my 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.
Rune

Recent Posts

Build and Deploy an AI App

Build and Deploy an AI App with Python Flask, OpenAI API, and Google Cloud: In…

5 days ago

Building Python REST APIs with gcloud Serverless

Python REST APIs with gcloud Serverless In the fast-paced world of application development, building robust…

5 days ago

Accelerate Your Web App Development Journey with Python and Docker

App Development with Python using Docker Are you an aspiring app developer looking to level…

6 days ago

Data Science Course Made Easy: Unlocking the Path to Success

Why Value-driven Data Science is the Key to Your Success In the world of data…

2 weeks ago

15 Machine Learning Projects: From Beginner to Pro

Harnessing the Power of Project-Based Learning and Python for Machine Learning Mastery In today's data-driven…

2 weeks ago

Unlock the Power of Python: 17 Project-Based Lessons from Zero to Machine Learning

Is Python the right choice for Machine Learning? Should you learn Python for Machine Learning?…

2 weeks ago