Harsh Dhamecha — July 12, 2021

This article was published as a part of the Data Science Blogathon

## Introduction

Have you ever wish to write better and shorter Python code? How to replicate traditional Switch cases in Python? I’ve got you covered. In this article, we will be discussing 5 Python Tips/Tricks for writing better and shorter code. So, let’s get started!

Note: Shorter doesn’t always mean better. Your code should be easy to read and understand.

We will be focusing on writing shorter and more readable code in this article. Specifically, we will learn:

• How to make large numbers more readable in code and output (10000000 to 10,000,000)?
• How to take a password as an input from a user without actually displaying it?
• How to use Dictionaries to implement Switch Cases?
• How to save memory using Generators?

1. Ternary Conditionals
2. Working with Large Numbers
3. Inputting Secret Information
4. Use Dictionary to Replicate Switch Cases
5. Use Generators to Save Memory
6. Bonus Tip
7. Summary
8. Endnotes

## Ternary Conditionals

Let us 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’s ain’t. So, to make your code pythonic, you can come up with something like the following:

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

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

We would get the same output in both ways.

Let’s move on to another trick.

## Working with Large Numbers

Now let us discuss my most favourite trick. Have you ever worked with large numbers? 1000000000 or 1,000,000,000; Which 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```

Isn’t it amazing? Indeed, it is.

## 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: ')
print('Logging In....')```

Output:

Image by Author

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
print('Logging In....')```

Output:

Image by Author

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

## Use Dictionary to Replicate Switch Cases

Most of us learn the C language as our first programming language. I’ve found the switch cases as the most simple yet important concept in C language. That was the first concept I learned in programming that has some real-world applications. We can think of its application in Customer Care calling.

Manier times, Beginner python programmers have doubts in their minds about applying switch cases using Python. We can use Python Dictionary to do that in which we define the function name as a key and function expression 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['subtract'](5, 2))
print(calc['mul'](5, 4))
print(calc['div'](10, 2))```

Output:

Image by Author

## Use Generators to Save Memory

Let’s say we have a very large list. So, here we have 10,000 elements in the list and we want to compute the square of each element. We can do that with the list comprehensions with the code which 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```

So, this is a perfect example where we can use generators. Similar to the list comprehensions, we can use generator comprehensions where we have parentheses instead of square braces. A Generator computes our elements lazily. So, it produces only one item at a time and only when asked for it. You may read more about the Generators here. The following program computes the square of each number up to 10000 using generator comprehensions.

```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’s a quite noticeable difference in memory usage. Now, try for the larger numbers on your own. You would see a huge difference!

## Use Interactive “_” Operator

Let us discuss our final tip. It’s a useful feature which not many of us know. Whenever we test an expression or call a function, the result dispatches to a temporary name, _ (an underscore). So, let us demonstrate this.

`2 + 3`
```# Output
# 5```

Now, execute the following code.

`print(_)`
```# Output
# 5```

Shocked by this? You may find all the tricks discussed in an article in my python notebook on Github.

## Summary

• How to make large numbers more readable in code and output (10000000 to 10,000,000)?
• How to take a password as an input from a user without actually displaying it?
• How to use Dictionaries to implement Switch Cases?
• How to save memory using Generators?

## Endnotes

Did I miss something important or want to share your thoughts? Comment down below, and I’ll get back to you.

I am Harsh Dhamecha, an aspiring Data Scientist. I am a final year undergrad student of Computer Science with a specialization in Artificial Intelligence. A self-motivated learner 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 sharing it.

If you have any queries, you can directly email me or connect with me on LinkedIn or Twitter for project collaboration. 