5 Python tips you MUST know to write better and shorter code.

Contents

This article was published as part of the Data Science Blogathon

Introduction

Have you ever wanted to write better and shorter Python code? How to replicate traditional Switch cases in Python? I got you covered. In this article, we will discuss 5 advice / Python tricks to write better and shorter code. Then let's get started!

Note: Shorter doesn't always mean better. Your code must be Easy to read and understand.

We will focus on writing shorter and More legible code in this article. Specifically, we will learn:

  • How to make large numbers more readable in code and output (10000000 a 10,000,000)?
  • How to take a password as input from a user without actually displaying it?
  • How to use dictionaries to implement switch cases?
  • How to save memory using generators?

Table of Contents

  1. Ternary conditionals
  2. Work with large numbers
  3. Enter secret information
  4. Use the dictionary to replicate switch cases
  5. Use generators to save memory
  6. Bonus tip
  7. Summary
  8. Final notes

Ternary conditionals

Let's take a situation where you are assigning a value to the variable based on some condition. You would probably write something like the following:

condition = False
if condition:
    x = 1
else:
    x = 0
print(x)

The above code works correctly, but do you think it is pythonic? It is not. Then, to make your code pythonic, you can find something like the following:

condition = False
x = 1 if condition else 0
print(x)

x = 1 if the else condition 0 is in plain English and self-explanatory. Therefore, makes our code shorter and easy to understand.

We would get the same result both ways.

Let's move on to another trick.

Work with large numbers

Now let's talk about my favorite trick. Have you ever worked with large numbers? 1000000000 O 1.000.000.000; Which is more readable? The second, truth? But if we try to do that in Python like num1 = 1,000,000,000, we would get an error.

But there is another method to do the same. We can use _ to separate the digits that do not affect our program. And we can use :, inside the string f to separate the output digits with 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

Isn't it amazing? In fact, it is.

Enter secret information

Let's say you are taking username and password as user input. I would surely go for the following approach.

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

Production:

99360secret-1-2083180

Author's Image

But anyone can see that password and that violates security. Then, to make it more secure, we would be using the get pass module.

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

Production:

74888secret-2-5784553

Author's Image

Have you noticed the difference? Ok, that sounds great. Let's move on to another trick.

Use the dictionary to replicate switch cases

Most of us learn the C language as our first programming language. I found switch boxes to be the simplest but most important concept in the C language. That was the first concept I learned in programming that has some real world applications. We can think about your application in Customer Service calls.

Many times, Beginning Python programmers have doubts about applying switch cases using Python. We can use the Python Dictionary to do that in which we define the name of the function as a key and the expression of the function as a value. The following program demonstrates the same.

calc = {
    'add': lambda x, Y: x + Y,
    'subtract': lambda x, Y: x - Y,
    'mul': lambda x, Y: x * Y,
    'div': lambda x, Y: x / Y 
}
# Smart way to call a function which is defined in a dictionary.
print(calc['add'](5, 4))
print(calc['subtract'](5, 2))
print(calc['mul'](5, 4))
print(calc['div'](10, 2))

Production:

75697dictionary-7961332

Author's Image

Use generators to save memory

Let's say we have a very large list. Then, here we have 10,000 elements in the list and we want to calculate the square of each element. We can do that with the list of comprehensions with the code that looks like the following.

import sys
squares_list = [i*i for i in range(10_000)]
# To print the size of a variable 
print(sys.getsizeof(squares_list, "bytes"))
# Output
# 87632

Then, this is a perfect example where we can use generators. Similar to comprehension lists, we can use generator understandings where we have parentheses instead of square braces. A generator calculates our elements lazily. Therefore, produces only one item at a time and only when requested. You can read more about generators here. The following program calculates the square of each number up to 10000 using generator understandings.

squares_gen = (i*i for i in range(10_000))
# To print the size of a variable 
print(sys.getsizeof(squares_gen, "bytes"))
# Output
# 128

That is quite a noticeable difference in memory usage.. Now, try to get the bigger numbers on your own. I would see a big difference!

Bonus tip

Use interactive operator “_”

Let's discuss our last tip. It's a useful feature that not many of us know about.. Whenever we test an expression or call a function, the result is sent to a temporary name, _ (an underscore). Then, let's prove this.

2 + 3
# Output
# 5

Now, run the following code.

print(_)
# Output
# 5

Surprised by this? You can find all the tricks discussed in an article in my python notebook on github.

Summary

That completes today's discussion.. In this article, we learned:

  • How to make large numbers more readable in code and output (10000000 a 10,000,000)?
  • How to take a password as input from a user without actually displaying it?
  • How to use dictionaries to implement switch cases?
  • How to save memory using generators?

Final notes

Thanks for reading this article!

I hope you enjoyed reading this article and it is worth dedicating your 10 minutes.

Did I miss something important or did I want to share your thoughts? Comment below and I will answer you.

About the Author

I am Harsh Dhamecha, an aspiring data scientist. I am a last year student of the Computer Science degree with a specialization in Artificial Intelligence. A motivated student who is eager to help the data science community as much as he can. I believe that knowledge is the currency of the 21st century and I love to share it.

If you have any query, can directly Email me or connect with me on LinkedIn O Twitter for project collaboration.

If you find this article knowledgeable and engaging, you can also read my other articles.

Keep reading! A special thanks to you 🙌

The media shown in this article is not the property of DataPeaker and is used at the author's discretion.

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.

Datapeaker