35 Best Python Tips and Tricks For Writing Better Code

15 min read
Share on:

Python is one of the most used programming languages in the world. It has a lot of features that will help a programmer to write better code. A lot of people think that writing code is all about getting the right answer. But in reality, it’s only a small part of the battle. The real challenge is writing code that is easy to understand, maintain, and extend.

Do you think in a similar way? But confused,

  • How you should write better python code?
  • What to improve and how to improve?

If so then you have reached the perfect place. In this article, I’m going to share with you the top 35 python tips and tricks that are going to help you to write better and easy to understandable python code.

This post is a compilation of python coding industry standards and a list of Python tips and tricks that every Python developer should know.

1. Python Tips for Conditional Expressions / Ternary Expression

Many times we use the if…else statement to check a condition and based on that we assign a value to a variable. It requires few lines of code and if we have to repeat the process multiple times in the program then it becomes lengthy. If you are facing the same thing then you are in luck I got a solution for you. You can use a ternary expression.

A ternary expression checks the condition and completes the assignment with just one line of code. As it’s a one-liner, it makes your code even more concise.

# Normal Programmers
if num % 2 == 0:
      result = "Number is divided by 2"
else:
      result = "Number is not divided by 2"

# Mentos Programmers
result = "Number is divided by 2" if num % 2 == 0 else  "Number is not divided by 2"

2. Use Python for multiple variable assignments

You can assign multiple variables with the same value or multiple values in a single line in python. In the first example, we are assigning 10 to the x, y, and z variables. We can do this by using this syntax.

 variable 1 = variable 2 = variable 3 = value

Similarly, if you are assigning different values then you try out this syntax.

 variable 1, variable 2, variable 3 = value1, value2, value3
# Normal Programmers
x = 10
y = 10
z = 10 

# Mentos Programmers
x = y = z = 10

x, y, z = 10, 20, 30

3. Working with Large Numbers with python

Now let us discuss my favorite trick. Have you ever worked with large numbers? 1000000000 or 1,000,000,000; Which one is more readable? The second one, right? But if we try to do that in Python like num1=1,000,000,000, we would get an error.

But there’s another method to do the same. We can use _ to separate the digits which do not affect our program. And we can use: inside the f string to separate the output digits by a comma. The following code demonstrates the same.

num1 = 1_000_000_000     # 1 billion
num2 = 10_000_000        # 10 million
total = num1 + num2
print(f'{total:,}')      # To separate the output digits with comma

# Output
# 1,010,000,000

4. Use list comprehension instead of raw for-loops

Have you ever worked with a list or tuple where you need to perform some operations on them?

But in the end, you wanted a list as an output? Then the next trick can definitely help you next time to save time and write concise code.

arr = [1, 2, 3, 4, 5, 6]
res = []

# Instead of this
for num in arr:
    if num % 2 == 0:
        res.append(num * 2)
    else:
        res.append(num)

# Use this
res = [(num * 2 if num % 2 == 0 else num) for num in arr]

5. Iterate with enumerate() instead of range(len())

All of us sometimes needed to iterate over a list while also needing to track the current item and index value. For that, we can use range(len()) but it’s hefty as we have to fetch the values separately. An easier solution for this problem is to use enumerate().

Enumerate() takes a list or tuple as a parameter and returns the result’s current index, value.

data = [1,2,3,-4,5]
# Normal Programmers
for i in range(len(data)):
      if data[i] < 0:
           data[i] = 0

# Mentos Programmers
for i, num in enumerate(data):
      if num < 0:
          data[i] = 0

6. Inputting Secret Information

Let’s say you are taking a username and password as input from the user. You would surely go with the following approach.

uname = input('Enter Username: ')
pwd = input('Enter password: ')
print('Logging In....')

#output
"""
Enter Username: Anup
Enter password: 12345
Loggin In..
"""

But anyone can see that password, and that breaches the security. So to make it more secure, we would be using the getpass() module.

from getpass import getpass
uname = input('Enter Username: ')
pwd = getpass('Enter password: ')
print('Logging In....')

#output
"""
Enter Username: Anup
Enter password: *****
Loggin In..
"""

1 thought on “35 Best Python Tips and Tricks For Writing Better Code”

Comments are closed.

AnupTechTips We would like to show you notifications for the latest news and updates.
Dismiss
Allow Notifications