5 Python Tricks That Will Make You Code Faster and Easier
Noah Olatoye

Noah Olatoye

243

5 Python Tricks That Will Make You Code Faster and Easier

 

The reason most people love Python Programming Language is because of its simplicity. You can read line of codes as if you are reading plain English sentences.

Not all Python Developers know of these tricks yet; luckily for you, you are about to learn something that will save you lots of stress going foreword.

 

1. Simple ways to format large integers (Underscore in Numeric Literals)

 

Programmers can use underscore literals write complex integers, floating points or hexadecimal addresses so that it is easy to read by a human.

# How will you render billion or million? 
2000000000

It becomes clearer when you use the underscore

2_000_000_000

#You can even group thousand. 1_0_0_0

 

This feature is available from Python 3.6 to the later versions. In other words, this won't work on lower versions like python 2.9.

Underscore can also be used for hexadecimal address and values

 

# Instead of declaring 
address = 0xCAFEF00D
flags = 0b0011111101001110

 

You can use the underscore to make it more readable

 

# grouping hexadecimal addresses by words
address = 0xCAFE_F00D

grouping bits into nibbles in a binary literal

flags = 0b_0011_1111_0100_1110

 

2. The f'' String Simple Formatting

With the Python f string formatting, you can combine both expressions, variables and strings without using tuple or calling the string format method.

 

student_name = 'Michael'
student_score = 80

Usually, we do something like this:

print('%s scored %d' %(student_name, student_score))

OUTPUT: Michael scored 80

 

The simpler way to reference the print string above is to use the f-string.

 

student_name = 'Michael'
student_score = 80

print(f'{student_name} scored {student_score}')

OUTPUT: Michael scored 80

 

It doesn't just end there, you can perform several expressions in the f-string.

 

student_name = 'Michael'
student_score = 80
total_score = 100

Subtract the students score from the total score.

print(f'{student_name} scored {student_score} and missed out {total_score - student_score} points from the total scores')

OUTPUT: Michael scored 80 and missed out 20 points from the total scores

 

You can also customise float value with a string literal.

 

interest_rate = 10.333333

print(f'If you invest today, you will get {interest_rate:.2f}% of the amount.')

#OUTPUT: If you invest today, you will get 10.33% of the amount.

 

You can see that we formatted the interested rate into two decimal places.

 

3. The more straightforward way to manage file path

Since operating systems and computers has various unique filling structures. It isn't easy to manage these file structures when trying to support multiple computers.

Fortunately for us, Python has a standard library called 'pathlib' that makes the process seamless.

Taking a look at an example:

 

from pathlib import Path

path_name = Path("folder_name") print(path_name)

OUTPUT: folder_name

 

We can include more subfolders in a way that it is readable.

 

from pathlib import Path

path_name = Path("folder_name") print(path_name)

OUTPUT: folder_name

Add subfolders

path = path_name / "sub_folder" / "sub_sub_folder" print(path)

output: folder_name/sub_folder/sub_sub_folder

 

We can also reference the root directory of the folder.

 

from pathlib import Path

path_name = Path("folder_name") print(path_name)

OUTPUT: folder_name

Add subfolders

path = path_name / "sub_folder" / "sub_sub_folder" print(path)

output: folder_name/sub_folder/sub_sub_folder

make path absolute

print(path.resolve())

OUTPUT: /Users/noaholatoye/some_folder/sub_folder/sub_sub_folder

 

4. Python Magic Command using IPython

Ipython makes it easy to easily declare python command in the terminal, Qt console and the web browser through the HTML notebook. You can read more about it here. It is a core Jypyter notebooks.

Some of the core features:

  • Comprehensive object introspection.
  • Input history, persistent across sessions.
  • Caching of output results during a session with automatically generated references.
  • Extensible tab completion, with support by default for completing of python variables and keywords, filenames and function keywords.
  • Extensible system of ‘magic’ commands for controlling the environment and performing many tasks related to IPython or the operating system.
  • A rich configuration system with easy switching between different setups (simpler than changing \$PYTHONSTARTUP environment variables every time).
  • Session logging and reloading.
  • Extensible syntax processing for special purpose situations.
  • Access to the system shell with user-extensible alias system.
  • Easily embeddable in other Python programs and GUIs.
  • Integrated access to the pdb debugger and the Python profiler.

 

5. A Simplified way of debugging your code

These features come with a PyCharm default debugger for Python projects. However, if you use editors like Sublime, Visual Studio Code, Vim or Atom, you can use the pdb module by importing and calling the function whenever you want your code to break.

 

foo()

import pdb; pdb.set_trace()

At this point, your code will stop and the interpreter will open

bar()

 

Python community has made it simpler from version 3.7. You can now use the breakpoint() function.

 

foo()

breakpoint()

At this point, your code will stop and the interpreter will open

bar()

 

Read more at PEP 553 -- Built-in breakpoint()

 

Conclusion

In wrapping it up, while these tips are not relatively new, still, most of the Python Developers are not aware of them, making it time-consuming creating some simple commands.

I was able to save lots of time when I started using these tricks. I hope you can apply them to your next projects.

A tech career with instinctHub

Ready to kickstart your tech career or enhance your existing knowledge? Contact us today for a dedicated instructor experience that will accelerate your learning and empower you to excel in the world of technology.

Our expert instructors are here to guide you every step of the way and help you achieve your goals. Don't miss out on this opportunity to unlock your full potential. Get in touch with us now and embark on an exciting journey towards a successful tech career.

Add Comments

First Name
Last Name
Say something:

Are you human? Solve this:

+ = ?

Post you may also like