10 mistakes you should NEVER make in Python | by Amado de Jesús Vázquez Acuña

Date:


When we start learning Python, many times, we come across bad practices. In this article, you will learn the best practices to 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 it beforehand, 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 commonly define one variable per line; however, there is a way to define multiple variables in just one line of code.

a,b,c = 12,56,128

In this simple way, we can define multiple 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 generally use * to invoke the models of the corresponding library. However, it does not make sense to call all the 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 an alias to it, followed by calling the methods that we are going to use.

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

We can also directly innovate the functions of the library of interest; either of these two ways is good.

3- Use “+” to concatenate.

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

Usually, we always use + to concatenate strings; however, it has the disadvantage that it is not so understandable.

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

We use formatted string literals, which allow concatenating variables regardless of the nature of the variable; it has the additional advantage that it is more understandable to read.

Chatathon by Chatbot Conference

4- Don’t use the lambda function.

def function(x):
return x**2

print(function(12))

Generally, when creating a function, we create a conventional function. There are occasions where the method we create is something simple but that we are going to use frequently.

function = lambda x: x**2

print(function(12))

We can create a lambda function for the same purpose, with the pleasant difference of making it simpler. If we want to create functions that are not so complex, it is much better to use lambda functions than conventional 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 learn, we are used to stating the if else statement in this way; 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"

In this way, reduce the if-else in a single line of code, making it more understandable 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)}')

Generally, we use multiple if statements according to the condition that is presented. It has the disadvantage of requiring an excessive amount of lines of 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 go around the sun by applying Keppler’s third law; as we can see, applying this strategy makes the code cleaner and easier to understand.

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 for loops; for example, in this case, we want to store only the even values.

import numpy as np

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

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

Using list compression, we can greatly reduce the lines of code to just one line.

8- Don’t use enumerate.

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 the name and surname of the person on the screen; for this, we use the function range() to define the indices and later print it based on the generated indices.

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 object index of the list, so we can save this step.

9- 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 a mistake similar to 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 us to use multiple lists at the same time, it is much more comfortable than using the index, and it also has the advantage that it is 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, more particularly with the methods to access them. We use keys() to access its keys, values() refers to extracting the values assigned to each key, and finally, items() allow us to extract both elements.

for key in consoles_dict:
print(key)

If we want to access the dictionary key, it is enough to apply a 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 over the for loop.

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

It is better to use the items() method and add the two values to iterate so we can get both the key and its value.

11-Do not 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 famous 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 numpy library greatly facilitates us when doing some mathematical calculations from something as simple as a sum to something more complex as Fourier transforms.

12- Do not use the 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 conventional Python list, and the IN operator will compare if the car we select is inside the list. We also rely on the if-else statement of a single line of code.

It may interest you.

Thank you very much for reading this little article. I hope you have learned a lot and that you put it into practice in your projects, be it Data Science, Computer Security, or web development. You can access the repository on GitHub.

Get Certified in ChatGPT + Conversational UX + Dialogflow



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Share post:

Share post:

Subscribe

spot_imgspot_img

Popular

More like this
Related

 PAW Patrol: The Mighty Movie – Watch in Dubai

PAW Patrol: The Mighty Movie is a 2023 American...

Watch Kannur Squad in Dubai – A Gripping Saga

Kannur Squad is a 2023 Malayalam-language action thriller film...

Ohio State vs Notre Dame – Excitement is in the Air

In one of the most anticipated games of the...

Reliable Postal and Courier Services Dubai – Fast & Secure Delivery

When it comes to sending and receiving packages and...