days
-4
-1
hours
0
-2
minutes
-2
-4
seconds
-1
-7
search
From newbie to master

Python tutorial: Best practices and common mistakes to avoid

N Subash Reddy
python
© Shutterstock / kumyin  

Coding is fun, especially when your “weapon of choice” is Python! There are, however, some common mistakes that keep you from having a fun time with Python. Here’s a quick tutorial to help you steer away from the most common mistakes.

Python is one of the high-level programming languages to develop web and desktop applications. Features of Python made it easy to understand, compile, execute and also can be translated to binary code like other programming languages.

Coding is fun. Coding is joy. Coding is everything to geeks. But when it comes to errors/mistakes, everyone does and can break all your emotions just like that. How about warnings? Who cares, unless they can terminate your program.

Common mistakes/Errors

Some of the most common errors/mistakes python programmers do are listed.

While working with Tuples

Remember tuples are immutable and cannot change values using any tuple id. String or Integer, tuples cannot be altered.

Above code is an example of TypeError in tuples

While working with discussions

Missing parts of an IF statement

Make sure of using proper and necessary colons and indentations while working with if statements as they will result in Syntax and Indentation errors.

SyntaxError

Can you find the error in the above code?

Even though the logic is correct, we will get a SyntaxError as we’ve missed colon(:) at the end of the if statement condition.

IndentationError

And now this you make sure with all the tab spaces provided, and now this will execute as expected.

Successful execution

Unnamed variables in a relational expression

Sometimes in a hurry, we may forget to define variables. I know it is silly, but we have some cases that show people commit such small errors. Working with values that are not defined will give you NameError. Silly yet useful one.

Incorrect names in a relational expression

Reusing code with copy paste will be taken care of renaming variables used. Unknowingly this will make you face errors, and put you in trouble sometimes.

SEE ALSO: Top 10 Python tools for machine learning and data science

While using Malford expression

While working with relational expressions, make sure you are using correct operators like double equals to compare equality, greater than, and less than.

Elif statement order of a relational expression

Order of conditions while working with if statements will have an impact on the output. Considering an example of grades, following order will give you incorrect results.

Elif order failure

In the above code, even though the logic in your mind works well, that’s is not the same while executing with code. Scoring 93 marks have resulted in showing Grade E, but that can’t be true. This shows the importance of the conditions order. Try to execute with different input values, and will probably end up giving you wrong outputs.

Following is the order that will implement the logic you have thought and will work as expected.

Proper Elif order execution

While working with function definitions

Indentation will be the key in executing of any python script. Most common error observed while working with Python is that developers, especially beginners try to start second instruction before properly closing the previous definition.

Python best practices

What makes you a professional from rest of generic programmers is the way you use your code. The less possible instructions to complete the task. Here are few tricks to make you stand out from the crowd.

Using enumerators while working with list

Here we take an example to print the list of fruits using generic way of executions. The following code works absolutely fine in executing instructions and give the desired output.

Generic solution

But recommended approach is to use enumerator that eliminates unwanted variable ‘i’ to iterate through the list.

Better way

Even though there is not much difference in the output, there exists a difference in the execution of instructions and the time taken to execute.

Understanding the use of ZIP while working with lists

Considering an example to print values from two or more lists with the same length, we have the following generic way and that works fine.

Generic execution

This is the most common way of solving the problem. But those who are aware of using ZIP has got merit in solving this case. Here is the solution using ZIP.

Better way

Swapping variables made easy

We have multiple algorithms to swap two numbers, of which most common was is using the third variable to swap.

Generic execution

The best feature to swap variables in a single line is available in python using tuple and packing.

Better way

The above code has got the same desired output but within a single line of code, we have done all the logic we knew to swap. Probably the coolest among the tricks.

Dictionary search made easy

Let us consider finding the state of the employee, using his name where we have name and state values as a pair in the dictionary. The most common way to execute the search is that trying to find the name in the dictionary and if available, we return the state, or failure will result as employee not found.

Generic execution

The same operation can be done using lesser lines of code using “get”. Here is the following code that will give you the same result with short codes.

Better way

Get method with dictionary does the same logic as the earlier code. It tries to find the first parameter key in the dictionary and returns value. Here in this case state is the value. If the key is not found, the second parameter to the get method acts as default one.

Practice make you perfect, but trying something new gives you wings. Learn something new with your experiments. What costs is your time, and what you gain is a priceless experience.

Author

N Subash Reddy

N Subash Reddy is senior content writer at Mindmajix. His writings focus on latest innovations in software and technical updates. Prior to Mindmajix, he was a web developer familiar with most of the web and UI technologies. He is a computer science post graduate. You can connect with Subash on LinkedIn and Twitter


Leave a Reply

12 Comments on "Python tutorial: Best practices and common mistakes to avoid"

avatar
400
  Subscribe  
Notify of
Beisi
Guest

it seems the “Elif statement” swapped the correct one with incorrect

chaos2007
Guest

Should the images for elif failure and proper be swapped? I might be misreading it, just curious.

Anonymous
Guest

Your elif examples are reversed.

Anonymous
Guest

Your elif examples appear to be reversed.

J R
Guest

The two images for the “elif” examples are swapped. The image with the correct code (Image-5-grades-success.jpg) is captioned with “Elif order failure”, and the image with the incorrect code (Image-6-grades-order-fail.jpg) is captioned with “Proper Elif order execution”.

David Mertz
Guest

It’s really hard to take seriously an article about Python 2.7 published in 2018. Maybe in 2008.

osunderdog
Guest

Dallas is not a state. ;)

Jim
Guest

This article is sorely in need of a grammatical review.