30 amazing Python tips to write better code

Posted by Simmo on Sat, 18 Dec 2021 00:29:55 +0100

Hello, I'm Chen Chen~

Python has become a very popular language because of the simplicity and readability of its code. It is one of the simplest languages you choose. If you are a beginner in the basic concepts of python, this is the best time to learn to write better code.

There are many techniques in python that can improve programs better than before. This article will help you understand the various techniques available in Python. Practice them until they become part of your programming habits.

I'll share 30 amazing Python tips to help you write better code. I'll share them twice~

Let's share 15 today. Let's have a look!

01 - multiple assignment of variables

Python allows us to assign values to multiple variables in a row. You can use commas to separate variables. Multitasking on the front line has many advantages. It can be used to assign multiple values to multiple variables or to assign multiple values to a single variable name. Let's make a problem statement in which we must assign values 50 and 60 to variables A and b. The general code is shown below.

a = 50  
b = 60 
print(a,b) 
print(type(a)) 
print(type(b)) 

Output

50  
60  
<class 'int'>  
<class 'int'> 

Condition I-value equals variable

When a variable is equal to multiple assignments, each value is stored in all variables.

a , b = 50 , 60 
print(a,b) 
print(type(a)) 
print(type(b)) 

Output

50  
60 
<class 'int'> 
<class 'int'> 

The two programs give the same results. This is the benefit of using a row value assignment.

Condition II - value greater than variable

Let's try increasing the number of values in a program. You can assign multiple values to a single variable. When assigning multiple values to a variable, we must use an asterisk before the variable name.

a , *b = 50 , 60 , 70 
print(a) 
print(b) 
print(type(a)) 
print(type(b)) 

Output

50 
[60, 70] 
<class 'int'> 
<class 'list'> 

The first value is assigned to the first variable. The second variable will collect values from the given values. This creates a list type object.

Condition III - multivariable one value

We can assign a value to multiple variables. Each variable will be separated by an equal sign.

a = b = c = 50 
print(a,b,c) 
print(type(a)) 
print(type(b)) 
print(type(c)) 

Output

50 50 50 
<class 'int'> 
<class 'int'> 
<class 'int'> 

02 - swap two variables

Exchange is the process of exchanging the values of two variables with each other. This is useful in many operations of computer science. Here, I write two main methods for programmers to exchange knowledge and the best solution.

Method I - use temporary variables

This method uses temporary variables to store some data. The following code is written using temporary variable names.

a , b = 50 , 60 
print(a,b) 
temp = a+b  
#a=50 b=60 temp=110 
b = a  
#a=50 b=50 temp=110 
a = temp-b  
#a=60 b=50 temp=110 
print("After swapping:",a,b) 

Output

50 60 
 
After swapping: 60 50 

Method II - do not use temporary variables

The following code exchanges variables without using temporary variables.

a , b = 50 , 60 
print(a,b) 
a = a+b  
#a=110 b=60 
b = a-b  
#a=110 b=50 
a = a-b  
#a=60 b=50 
print("After swapping:",a,b) 

Output

50 60 
 
After swapping: 60 50 

Method III excellent solution in Python

This is another way to exchange variables using python. In the previous section, we looked at multiple assignments. We can use the concept of exchange.

a , b = 50 , 60 
print(a,b) 
a , b = b , a 
print("After swapping",a,b) 

Output

50 60 
 
After swapping 60 50 

03 - reverse string

Another cool trick is to reverse strings in python. The concept used to invert strings is called string slicing. You can reverse any string with the symbol [:: - 1] after the variable name.

my_string = "MY STRING" 
rev_string = my_string[::-1] 
print(rev_string) 

Output

GNIRTS YM 

04 - split words in one line

No special algorithm is required to segment words into one line. To do this, we can use the keyword split(). Here, I write two ways to segment words.

Method 1 - use iterative method

my_string = "This is a string in Python" 
start = 0 
end = 0 
my_list = [] 
for x in my_string:  
    end=end+1  
    if(x==' '):  
    my_list.append(my_string[start:end])  
    start=end+1 
    my_list.append(my_string[start:end+1]) 
print(my_list) 

Output

['This ', 'is ', 'a ', 'string ', 'in ', 'Python']

Method II - use segmentation function

my_string = "This is a string in Python" 
my_list = my_string.split(' ') 
print(my_list) 

Output

['This ', 'is ', 'a ', 'string ', 'in ', 'Python'] 

05 - line up the word list

This is the opposite of the previous process. In this section, we will use the join function to convert the word list into a single line. The syntax for using the join function is given below.

Syntax: '' join(string)

my_list = ['This' , 'is' , 'a' , 'string' , 'in' , 'Python'] 
my_string = " ".join(my_list) 

Output

This is a string in Python 

06 - print string multiple times

We can print the string multiple times using the multiplication operator. This is a very effective way to repeat strings.

n = int(input("How many times you need to repeat:")) 
my_string = "Python\n" 
print(my_string*n) 

Output

How many times you need to repeat:3 
 
PythonPythonPython 

07 join two strings using the addition operator

You can connect various strings without using the join function. We can do this using only the addition operator (+).

a = "I Love " 
b = "Python" 
print(a+b) 

Output

I Love Python 

08 - multiple conditional operators

Two can combine two or more conditional operators in a program. We can use logical operators. However, you can get the same result through the link operator. For example, if we need to print something when the value of the variable is greater than 10 and less than 20, the code will be similar to the following.

a = 15 
if (a>10 and a<20):  
    print("Hi") 

Instead, we can combine conditional operators into a single expression.

a = 15 
if (10 < a < 20):  
    print("Hi") 

Output

Hi 

09 - find the most frequent elements in the list

The element that appears most of the time in the list will then become the most frequent element in the list. The following code snippet will help you get the most frequent elements from the list.

my_list = [1,2,3,1,1,4,2,1] 
most_frequent = max(set(my_list),key=my_list.count) 
print(most_frequent) 

Output

1 

10 - find the appearance of all elements in the list

The previous code will provide the most frequent values. If we need to know the occurrence of all unique elements in the list, we can use the collection module. This collection is a great module in python, which provides powerful functions. The Counter method provides a dictionary with elements and occurrence pairs.

from collections import Counter 
my_list = [1,2,3,1,4,1,5,5] 
print(Counter(my_list)) 

Output

Counter({1: 3, 5: 2, 2: 1, 3: 1, 4: 1}) 

11 - check the puzzle of two strings

If a string consists of characters in another string, both strings are puzzles. We can use the same Counter method in the collections module.

from collections import Counter 
my_string_1 = "RACECAR" 
my_string_2 = "CARRACE" 
 
if(Counter(my_string_1) == Counter(my_string_2)):  
    print("Anagram") 
else: print("Not Anagram") 

Output

Anagram 

12 - create a sequence of numbers with ranges

The function range() is useful for creating a sequence of numbers. It can be useful in many code snippets. The syntax for the scope function is written here.

Syntax: range (start, end, step)

Let's try to create an even list.

my_list = list(range(2,20,2)) 
print(my_list) 

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18] 

13 - repeated elements

Similar to string multiplication, we can use the multiplication operator to create a list of elements that are filled multiple times.

my_list = [3] 
my_list = my_list*5 
print(my_list) 

Output

[3, 3, 3, 3, 3] 

14 - using conditions in ternary operators

In most cases, we use nested conditional structures in Python. In addition to using nested structures, you can replace a line with the help of ternary operators. The syntax is given below.

Syntax: if True then Statement1 else Statement2

if age > 20 then age = 25, print("czz")else print("unqualified")

Output

qualified 

15 - derivation of expressions using Python lists

List derivation expressions are a very compact way to create a list from another list. Look at the code below. The first is written using simple iterations, and the second is understood using lists.

square_list = [] 
for x in range(1,10):  
    temp = x**2 square_list.append(temp) 
print(square_list) 

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81] 

Derive expressions using lists

square_list = [x**2 for x in range(1,10)] 
print(square_list) 

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81] 

last

Well, today's sharing is over. The other half will share with you next time