Python - 5 Cool Tricks

Python - 5 Cool Tricks

Featured on Hashnode

1. Readable long number

If you are declaring a long number (eg. 10 million) in your code, it would be much harder for other guys to read it (10000000 ❌). So to avoid this, python has a special feature for you. You can split the numbers with "_". This is just for the readability, it would still be considered as a number with no underscores.

Here's an example.

big_number = 10_000_000
print(big_number)

# Output: 10000000

2. Define infinite

Finally there is a value for Infinite 😄 (just kidding), we can define infinite in python and of course compare it with some real numbers.

Here's an example.

infinity = float('Inf')

if 9999999999999999999 > infinity:
    print("This will never happen")
else:
    print("Infinity wins!!")

# Output: Infinity wins!!

3. Else for everything

Unlike other programming languages, you can add else to not only for if conditions but also for looping statements (for, while, etc). If you want to execute something at the end of the iteration, this is a right choice for you.

Note: else won't be executed if you are breaking the loop.

Here's an example.

for i in range(5):
    print(i, end=" ")
else:
    print("Loop ends here.")

# Output: 0 1 2 3 4 Loop ends here.

4. Swap it like a Pro

Swapping two variables is very simple, all you have to do is just swap your variable's positions (I'm not kidding, this is real 😇).

Here's an example.

a = 5
b = 4
a, b = b, a
print(a, b)

# Output: 4, 5

5. Python will tell you a joke, if you are bored!

Just import antigravity in your IDE and thank me later! It will open up a web browser that points to the classic XKCD comic mentioning Python.

Here's an example.

import antigravity

BTW, this is my first post 🤘 Wish me luck !