top of page
  • Writer's pictureAdmin

Python Tips and Tricks For Writing Better Code

Improve the quality of your code by using these tips and tricks.


1. F - Strings


Python 3.6 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler.

To create an f-string, prefix the string with the letter “ f ”.



name = "Admin"
age = "21"
instagram = "ps.programmer"

To not deal with string concatenation or using commas inside the print statement, you can use Python's improved string formatting syntax "f-strings".

Simply put a lowercase or uppercase letter "f" before the string with the variables or expressions inside the curly braces.




 

2. The Help Function


The Python help function is used to look up the documentation of modules, functions, classes, keywords etc.


Simply put an object inside the help function to get the documentation for that object.



 

3. Comparison Operator Chaining


Normally to check more than two conditions, you would have to use logical operators such as and / or




if a < b and b < c :

In Python there is a better way to write this using Comparison Operator Chaining.

We can write it as follows:



if a < b < c : 

 

4. List Comprehensions


Rather than creating an empty list and adding each element to the end, you can simply define the list and its contents at the same time by following this format.



list1 = [expression for item in iterable (if conditional)]

For Example :



 

5. Assigning Multiple Variables in One Line


You can assign multiple values to multiple variables by separating variables and values with commas :


For Example :



 

6. Swap Variables


In Python, there is a simple one-line construct to swap variables, similar to the concept of assignments of values to multiple variables in one line.



temp = x
x = y
y = temp

For Example


 

7. Create an Enum


Enum is a class in Python for creating enumerations, which are a set of symbolic names attached to unique, constant values.

For this, it is necessary to create a class.


For Example :



Thank you all of you for reading this post I hope these tips will help you. And if you got your own tips don't forget to comment it in the comment section below.



 

6 views0 comments
bottom of page