coding hacks

Top 10 Coding Hacks in Python Every Developer Should Know

by Olawale Moses Oyewole

Coding is not easy at times but there are simple tricks that can make your coding experience easier and faster.

Most developers prefer using Python programming language right from the developmental phase of their project until they are ready to launch it, this can be attributed to Python’s transparent and simple coding logic. However, coding may be tiring when projects are too much.

Using Python tricks can simplify your coding experience and shorten the time spent on Python projects.

In this article, I have provided a list of some Python coding hacks that every developer should know.

Top 10 Coding Hacks in Python 

  1. The trimming coding hack

 The trimming coding trick is used for removing unwanted data. While using strings, whitespaces and other characters may make your code look incoherent, trimming helps to scrape these unwanted characters and texts.

To tackle this, use the Python hack named strip(). This coding hack can be used for a string or list of string

trimming hack

An example of trimming coding in python

  • Trimming A String

data = “\n\n\n \t McDonald Restaurant \t \n\n\n “

Print (data.strip())

–o/p—–

McDonald Restaurant

  • Trimming List of Strings

data = [“n\n\n Burger \t”, “\n\t Pizza \t “]

cleaned_data = [i.strip() for I in data]

print (cleaned_data)

–o/p—–

[“Burger”, “Pizza”]

  1. Shortening (of libraries name) python trick

Python has huge libraries where developers access different codes. However, there may be a problem when you need to use the library often. Shortening is the Python trick that can be used to shorten the name of the library so that it is easily accessible the next time.

Shortening is done using the “as” keyword. This keyword makes it possible to recognize the library the next time you want to access it.

## Normal Way

Import numpy

Import speech_recognition

## Shorten Name

Import numpy as np

Import speech_recognition as sr

  1. Slicing trick

Slicing is a coding hack used to access sequences such as lists, tuples, and strings. Slicing is used to delete or modify any item in the sequence; this gives your code a readable, succinct and clean structure.

  • Checking For Palindrome 

name = “wow”

print (name== [: :-1])

——————-

True

  • Retrieving Even Numbers from a Natural Sequence 

natural_numbers = [1,2,3,4,5,6,7,8,9,10]

even_numbers = natural_numbers [1: :2]

print (even_numbers)

——————-

[2,4,6,8,10]

  1. File sharing coding hack

With the file sharing coding hack, you can create a file sharing server (a free FTP server) which can be used to share files between your PC and another PC or mobile device. File sharing makes it easy to access your files on another device.

Follow the steps below:

python –m http.server 4000

For this, the port range to use should be 0 to 65353. The executed code makes your server run on 127.0.0.1:4000

The next thing is to open the browser of the device and type;

YOUR_COMPUTER_IP_ADDRESS: PORT_NUMBER

You will get your computer IP address by performing “ipconfig” on your PC terminal; this gives you the IPv4 address. 

For instance, if 192.168.39.145 is your IP address and 4000 is the Port Number; then 192.168.39.145.4000 will serve as where the file-sharing server will run. 

Read Also: Python for Beginners: Advantages of Learning Python Language

  1. Type-checking trick

To know more about any variable, you need to check the variable type, and you may do this over and over again during your Python project. The type-checking Python trick helps you classify variables using two object parameters.

With the use of the “isinstance()” function, you can return a Boolean if the object is an instance of the stated class. This function makes it a whole lot easier to check the variable type.

Step

Class ABC:

    def_init_(self, name, age, salary):

        self.name = name

        self.age = age

        self.salary = salary

Emp1 = ABC(“Moses”, 56,45000)

Print(isinstance(Emp1, ABC))    ## True

data = [2,3,4,5,6]

print(isinstance(data,list))    ## True

print(isinstance(data,ABC))    ## False

Read Also: Transitioning into Tech in Nigeria: A Comprehensive Guide

  1. The “_” operator python trick

Although the “_” operator is popularly used to stipulate data, it can be used as a valid variable name and character for Python coding. Python docs use this character to save the result of prior calculations.

  • Using the “_” operator as a variable

_ = 20

a = 30

Sum = _ + a

print(sum)

30

  • Using the “_” operator to restore the result of the prior calculation

>>>200+300

500

>>>_*2

1000

  1. The frequency python trick

Sometimes, you may want to know the total number of times a particular number or set of numbers appear in a given data; the best way to do this is by using the frequency coding hack which counts the occurrence of the elements.

Steps

From collection import

Counter

data = [96, 96, 95, 94, 96, 94, 95, 92, 92,91, 99, 90]

occurrence = Counter (data)

print(occurrence)

Counter ({99: 1, 96: 3, 95: 2, 94: 2, 92: 2, 91: 1, 90: 1})

  1. The “get” coding hack

 It is normal for programmers to use square brackets when accessing an element from Dictionaries or any other data structure. However, if you will reduce coding errors, the “get” coding hack is the best. The “get” coding hack helps to look for the dictionary elements without any code error prompt.

Steps

data_dict = {a:1, b:2, c:3}

print(data_dict[‘d’])    ##

KeyError : ‘d’

Print(data_dict.get(‘d’))    ##

None

Read Also: 5 of The Best Programming Languages to Learn As A Beginner

  1. The exception coding hack

Sometimes a code is interrupted during its execution, this condition is termed exception. The “try” and “except” block is used for Python exception. A code that will be executed is in the “try” block while if there is any fault in the “try” block, the “except” block code will be executed. The “except” block has made an exception to the initial error of the “try” block.

Steps

  • Exception 

a = 8

b = 0

print (a/b)     ##

ZeroDivisionError: division by zero

  • Exception Handling 

try:

    a = 8

    b = 0

    print (a/b)

except:

    print(“Can’t Divide Number With 0”)

Can’t Divide Number With 0

  1. One-line mathematical expression solution hack

coding

An example of One-line mathematical expression solution hack

The one-line solution coding hack uses three main input parameters. These parameters are the direct value reference, the reference to a variable and the exact mathematical expression to be evaluated. The function for carrying out this coding hack is “eval()”. For instance;

  • Basic Evaluation 

print(eval(‘2+5-3*34//2%6’))            ##4

‘ ‘ ‘ Reference To a Variable ‘ ‘ ‘

num = 6

print(eval(‘2+5-3*34//2%x’, {‘x’: num}))        ##4

  • Direct Value Reference

print(eval(‘2+5-3*34//2%x’), {}, {‘x’: 6}))        ##4

Conclusion

Every Python programmer would have, at one time or another wished that there were easier ways or tricks to write codes or evaluate expressions. There are easier tricks if you are willing to adjust to the new Python culture.

These Python tricks make your work effective and readable. Besides, if you don’t want to spend several hours in front of your PC, you might need to apply some of the coding hacks discussed here.

Hey! Join the Insight Whatsapp Community right away. As a freelancer and an aspiring programmer, we have a lot to offer you. If you are also inspired by this post, please follow our Instagram page to learn about future inspiring articles. 

About Author

Avatar of Olawale Moses Oyewole
Olawale Moses Oyewole
Olawale Moses Oyewole is a digital strategist who stays on top of current events and curate informative and engaging articles for his readers. He helps brand locate their target audience and enhance their online visibility.

Related Posts

Leave a Comment

× Say hi
-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00