10 Mistakes You Should Never Make in Python | By Amado de Jesus Vázquez Acuna

Amado de Jesus Vasquez Acuña
Become human.  Journal of Artificial Intelligence

When we start learning Python, many times we come across bad practices. In this article you will learn best practices take your Python developer level to the next level.

I remember when I first started learning Python, I made a lot of mistakes that, if I had known about them in advance, would have allowed me to speed up the learning curve.

1- Do not define variables on a single line.

a = 12
b = 56
c = 128

We usually define one variable per line; however, there is an option to define multiple variables in just one line of code.

a,b,c = 12,56,128

In this simple way, we can define many variables, which makes the code easier to read.

2- Use * to import modules.

from numpy import *
numbers = arange(1,10,step = 10)
print(mean(numbers))

We usually use * to call the corresponding library models. However, it doesn’t make sense to call all modules if we are only interested in specific library functions.

import numpy as np
numbers = np.arange(1,10,step = 10)
print(np.mean(numbers))

Import the library of interest, in this case numpy, and we can assign it an alias followed by calling the methods we’re going to use.

from numpy import arange,mean
numbers = arange(1,10,step = 10)
print(mean(numbers))

We can also directly innovate library functions of interest; either way is fine.

3- Use “+” to connect.

name,year = "Amado",22
print("My name is " + name + " and I am " + str(year) + " years old")

Normally, we always use + to join strings; however, it has the disadvantage that it is not very understandable.

name,year = "Amado",22
print(f"My name is {name} and Im {year} years old")

We use formatted string literals that allow us to concatenate variables regardless of the nature of the variable; it has the added benefit of being easier to read.

Chatathon by Chatbot Conference

4- Do not use lambda function.

def function(x):
return x**2

print(function(12))

Generally, when creating a function, we create a conditional function. There are times when the method we’ve created is something simple, but one we’re going to use often.

function = lambda x: x**2

print(function(12))

For the same purpose, we can create a lambda function to make it simpler with a nice difference. If we want to create less complex functions, it is much better to use lambda functions than regular Python functions.

5- Using If Else from multiple lines of code.

age = 22

if age>=18:
print('You are of age')

else:

print('You are not of age')

Usually, when we study, we are used to expressing the if else statement like this: however, it can be simplified to just one line of code.

age = 22
"You are of age" if age>=18 else "You are not of age"

This way, reduce the if-else to one line of code, making it easier to read.

6- Using multiple conditional If statements.

kepler_third_law = lambda ua: (np.round(np.sqrt(ua**3),1))

def calculate_years(planet):
planet = planet.lower()
if planet == "mercury":
ua = 0.387
print(f'Number of planet years Mercury: {kepler_third_law(ua)}')

if planet == "venus":
ua = 0.723
print(f'Number of planet years Venus: {kepler_third_law(ua)}')

if planet == "earth":
ua = 1
print(f'Number of planet years Earth: {kepler_third_law(ua)}')

if planet == "mars":
ua = 1.524
print(f'Number of planet years Mars: {kepler_third_law(ua)}')

if planet == "earth":
ua = 1
print(f'Number of planet years Earth: {kepler_third_law(ua)}')

if planet == "jupiter":
ua = 5.208
print(f'Number of planet years Jupiter: {kepler_third_law(ua)}')

if planet == "saturn":
ua = 9.539
print(f'Number of planet years Saturn: {kepler_third_law(ua)}')

if planet == "uranus":
ua = 19.182
print(f'Number of planet years Uranus: {kepler_third_law(ua)}')

if planet == "neptune":
ua = 30.058
print(f'Number of planet years Neptune: {kepler_third_law(ua)}')

if planet == "pluto":
ua = 39.439
print(f'Number of planet years Pluto: {kepler_third_law(ua)}')

In general, we use multiple if statements according to the condition presented. It has the disadvantage of requiring too much code.

import numpy as np

kepler_third_law = lambda ua: (np.round(np.sqrt(ua**3),1))

def calculate_years(planet):

planet = planet.lower()

ua_dict = {'saturn':9.539,
'earth':1,
'mercury':0.387,
'venus':0.723,
'jupiter':5.203,
'uranus':19.182,
'pluto':39.439,
'mars':1.524}

years = kepler_third_law(ua_dict[planet])

return f'Number of planet years {planet}: {years}'

Instead of using multiple if statements, we create a dictionary where we store the AUs of the planets to later calculate the number of years it takes to orbit the Sun using Keppler’s third law; as we can see, using this strategy makes the code cleaner and more understandable.

7- Don’t use list comprehension.

import numpy as np

numbers = np.arange(1,20+1,step = 1)

par_numbers = []

for number in numbers:

if number %2==0:

par_numbers.append(number)

Generally, if we want to store elements in a list according to a given condition, we use loops; For example, in this case we want to store only even values.

import numpy as np

numbers = np.arange(1,20+1,step = 1)

[n for n in numbers if n % 2 == 0]

By using list compression, we can significantly reduce lines of code to just one line.

8- Do not use enumeration.

names = ['Amado','John','Artemio']
last_name = ['Vazquez','Jobs','Lara']

for i in range(len(names)):
print(f'{names[i]} {last_name[i]}')

Suppose we want to print a person’s name and surname on the screen. for that we use the function range () set the indexes and later print based on the generated indexes.

names = ['Amado','John','Artemio']
last_name = ['Vazquez','Jobs','Lara']

for i,name in enumerate(names):
print(f'{name} {last_name[i]}')

Using the enumerate function returns the index of the list object, so we can save this step.

9- D:o do not use zip

manufacturer = ['Infiniti','Mazda','Nissan','BMW']
model = ['Q50','Mazda 6','Altima','3 Series']
engine = [3.0,2.5,2.0,2.0]

for i in range(len(manufacturer)):
print(f'{manufacturer[i]} {model[i]} {engine[i]}')

Here we make the same mistake as the previous one, with the difference that here we want to print three lists in harmony.

manufacturers = ['Infiniti','Mazda','Nissan','BMW']
models = ['Q50','Mazda 6','Altima','3 Series']
engines = [3.0,2.5,2.0,2.0]

for (manufacturer,model,engine) in zip(manufacturers,models,engines):
print(f'{manufacturer} {model} {engine}')

Using the zip method allows you to use multiple lists at once, which is much more convenient than using an index, and also has the advantage of being much easier to understand.

10- Keys()/Items()

consoles_dict = {'PS5':499,
'PS5 Digital':399,
'Xbox Series S':299,
'Xbox Series X':499}

consoles_dict.keys() #'PS5','PS5 Digital','Xbox Series S','Xbox Series X'
consoles_dict.values() # 499,399,299,499
consoles_dict.items()

Sometimes we misuse dictionaries, especially with regard to their access methods. We use keys() to access the keys, values() is about extracting the values ​​assigned to each key, and finally, items() allows us to extract the two items.

for key in consoles_dict:
print(key)

If we want to access a dictionary key, it is enough to apply the cycle to the dictionary of interest.

for key in consoles_dict:
print(consoles_dict[key])

If we want to access the value of the dictionary, it is enough to assign it the name of the key in the for loop.

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

Better to use the items() method and add both values ​​to iterate over so we can get both the key and its value.

11-Don’t rely on modules.

sum_ = 0

for number in range(1,10+1):
sum_ += number

print(sum_/10)

Some libraries can make life easier. for example, there is a library called numpy that is used to perform mathematical calculations. Some libraries can make life easier instead of programming from scratch. For example, there is a very popular library in data science that is used to perform complex calculations.

import numpy as np

numbers = np.arange(1,10+1,1)

print(np.mean(numbers))

The numb library helps us a lot when doing math calculations from something as simple as a sum to something more complex like Fourier transforms.

12- Do not use IN

car_model = "Maxima"
if car_model == "Altima" or car_model == "Maxima" or car_model == "Q50" or car_model == "Q60":
print('mMdel available')

Instead of using a long conditional statement, we can support the IN conditional.

car_models = ['Altima','Maxima','Q50','Q60']
car_model = "Maxima"
'Model avaliable' if car_model in car_models else 'Model not avaliable'

We create a regular Python list and the IN operator will compare if the machine we selected is inside the list. We also rely on the if-else statement in a single line of code.

It might interest you.

Thank you very much to read this short article. I hope you learned a lot and apply it to your projects, whether it’s data science, computer security, or web development. You can access the repository GitHub:.

Get certified in ChatGPT + Conversational UX + Dialogflow

Source link