This article is participating in Python Theme Month. See the link to the event for more details

directory

๐Ÿฅ‡ 1. Arrange ๐Ÿ‘“ in itertools 2. Single-line conditional expression ๐Ÿš‹ 3. Invert the string ๐Ÿฑ๐Ÿ 4. Use Assert to handle ๐ŸŽช 5. Use split ๐ŸŽข for multiple inputs 6. Use zip() transpose ๐ŸŽˆ 7. Resource Context Manager ๐ŸŽก 8. Underscore as separator ๐ŸŽ  9. Try f string format ๐Ÿงฆ 10. Use this trick to swap the integer ๐ŸŽฑ 11. Use lambda instead of the function ๐ŸŽณ 12. Print multiple times without a loop ๐Ÿฅ… 13. Unpack strings into variables ๐ŸŽฏ 14. Use Map for list understanding ๐ŸŽด 15. Remove duplicates from the list ๐Ÿซ 16. Print the condition in the statement ๐Ÿบ 17. Condition list All and Any ๐Ÿ– 18. Merge the two dictionaries ๐Ÿš’ 19. check execution time ๐Ÿš€ 20. check function libraries ๐Ÿบ 20 Python tips everyone must know | Python topics month ๐Ÿงต More related articles

๐Ÿฅ‡ 1. Arrange using itertools

In this program, we import a built-in module called Itertools. Using Itertools, you can find all permutations of a given string. There are many methods in Itertools, and you can try combinations and other methods.

import itertools
name= 'Python'
for i in itertools.permutations(name):
    print(i)                                                                        
Copy the code

Return to the directory


๐Ÿ‘“ 2. Single-line conditional expressions

This conditional expression was added to Python version 2.5. This can be used with the A if condition else B syntax. First, the condition is evaluated and returned based on its Boolean value. If true, return A; otherwise, if false, return B.

x=10
y=100
res = x if x>y else y
print(f"The greater number is {res}")    
Copy the code

Return to the directory


๐ŸŒน 3. Reverse the string

In this program, we use the extension slice to reverse the string, which uses the [begin:end:step] syntax. So when we skip the start, end, and step, we pass (-1) as the value. This reverses the given string.

string = "medium"
reverse_string = string[::-1]
print(f"The reversed string is {reverse_string}")  
Copy the code

Return to the directory


๐Ÿฑ๐Ÿ 4. Use Assert to handle exceptions

Exception handling is a very important concept in programming. Prints the error statement using the assert keyword and the given condition. If the given condition is not true, it prints an error message and terminates the program.

x = int(input("enter a number to divide ")) 
assert x<=-1 and x>0.'Number should be greater than 0' 
ans = 100/x 
print(f'The output is {ans}')
Copy the code

Return to the directory


๐ŸŽช 5. Split multiple inputs

Split () is one of the string methods that splits a string into a list. The default delimiter used in this method is space. In this program, instead of creating three repeating lines for the input operation, you replace them with one.

a,b,c = input("Enter the value for a, b, c :").split()
print(a)
print(b)
print(c)    
Copy the code

Return to the directory


๐ŸŽข 6. Use zip() transpose

The Zip function takes any number of iterable objects from different columns and aggregates the corresponding tuples. The asterisk (*) operator is used to decompress the list. The list is later changed to the transpose of the given list.

matrix=[[1.2], [3.4], [5.6]]
trans=zip( *matrix)
print(list(trans))   
Copy the code

Return to the directory


๐ŸŽˆ 7. Resource context Manager

Resource management is one of the most important tasks in programming. Accessing and releasing files, locks, and other resources is a busy business. If resources are not shut down correctly, several problems can result, including memory leaks. To solve this problem, instead of using the open and close methods every time, use the context manager shown in the code snippet.

with open("demo.txt", mode="w") as file:
    file.write('Hola! ')  
Copy the code

Return to the directory


๐ŸŽก 8. The underscore is used as the separator

When using large numbers in a program, using underscores instead of commas as separators can improve readability. Python syntax does not recognize underscores. It is represented by an underscore, represents numbers in the preferred format, and is readable.

x = 10 _000_000_000
print(f" It is Ten Billion: {x}")                                                       
Copy the code

Return to the directory


๐ŸŽ  9. Try the f string format

The F string format was introduced in Python 3.6. It is the easiest way to format a string. Using the F-string format instead of the traditional format makes the code easier to understand.

Name = input("Enter your name ")
print(f'Hello{Name}! This is a Python Example')    
Copy the code

Return to the directory


๐Ÿงฆ 10. Swap integers with this trick

Note that swapping integers is done without the use of temporary variables. Python evaluates expressions from left to right, but in assignment, the right side is evaluated first. This creates tuples for the right-hand variables (b and a), whose values are assigned from the left-hand variables. This process facilitates the exchange of variables.

a,b = input("Enter the value for a, b :").split()
a,b = b,a
print(a,b) 
Copy the code

Return to the directory


๐ŸŽฑ 11. Use lambda instead of functions

Lambda is one of the most powerful functions, also known as anonymous functions. It does not require a name or function definition or return statement. Ordinary functions use the def keyword, while lambda functions use the lambda keyword. It works like a function, except it only applies to one expression.

x = lambda a, b : a + b
print(x(1.2))  
Copy the code

Return to the directory


๐ŸŽณ 12. No loop for multiple prints

In this program, we try to print statements in a single line instead of using loops multiple times. The asterisk (*) enables you to print the statement a specified number of times.

print("This is a Python example to print this 100 times\n" *100) 
Copy the code

Return to the directory


๐Ÿฅ… 13. Unpack strings into variables

A sequence or a string can be unwrapped into different variables. In this program, the Python string letters are unpacked into variables. The output of the program will be P, y, t.

name='Python'
a,b,c,d,e,f =name
print(a)
print(b)
print(c)                                                                          
Copy the code

Return to the directory


๐ŸŽฏ 14. Use Map to understand lists

In this program, we try to add elements to the list. To do this, we use lambda functions in combination with map and List Comprehension. The output of this program will be [12, 15, 18].

num1=[1.2.3]
num2= [4.5.6]
num3=[7.8.9]
result= map(lambda x,y,z:x+y+z,num1,num2,num3)
print(list(result))  
Copy the code

Return to the directory


๐ŸŽด 15. Delete duplicates from the list

In this program, we try to remove duplicates from the list. One thing to remember is that collections are not allowed to repeat. We pass the list to set() and change it to a list again, removing all duplicate elements from the list.

old_list = [1.2.2.3.3.4.5.5.6]
new_list = list(set(old_list))
print(new_list)     
Copy the code

Return to the directory


๐Ÿซ 16. Print conditions in statements

This program is interesting and contains quite a few operations. First, the input method is executed, and then the input value is changed to an integer. It then checks the condition and returns a Boolean value. If it returns a non-zero number, an odd number will be the output, or if it returns zero, then an even number will be the output.

print("odd" if int(input("enter the value")) %2 else "even")  
Copy the code

Return to the directory


๐Ÿบ 17. Conditional list All and Any

In this program, we examine the list of conditions one at a time. There are two functions: all() and any(). As the name implies, when we use all(), all conditions must be true. And when any() is used, the block is executed even if one of the conditions is true.

Marks = 350
Percentage = 60
Passed = 5
Conditions = [Marks>200, Percentage>50,Passed>4]
if(all(Conditions)):
    print("Hired for a company A")
elif(any(Conditions)):
    print("Hired for a company B")
else:
    print("Rejected")   
Copy the code

Return to the directory


๐Ÿ– 18. Merge the two dictionaries

This one is now deprecated

In this program, we try to merge two dictionaries. Please note that in this program, you can use “|” to merge operator.

Household = {'Groceries':'100'.'Electricity':'150'}
Travel = {'Food':'50'.'Accomodation':'122'.'Transport':'70'}
Expense = Household | Travel
print(Expense)  
Copy the code

Return to the directory


๐Ÿš’ 19. Check the execution time

Check the execution time of the program by importing the timeit package. In this program, the execution time to form a list of 1 to 1000.

import timeit
execution_time = timeit.timeit('list (range (0) 1100)')
print(execution_time)    
Copy the code

Return to the directory


๐Ÿš€ 20. Check the library

In this program, we try to check the library of the function. All itertools properties and modules are printed using this program.

import itertools
print(dir(itertools))  
Copy the code

Return to the directory


๐Ÿบ 20 Python tips everyone must know | Python Theme month

So, here are 20 Python tricks everyone must know. I hope you have understood everything clearly. Because these are useful when we use Python.

If you enjoyed this article and are interested in seeing more of it, you can check out the source code for all my originals and works here:

Making, Gitee

More on this at ๐Ÿงต

  • 30 Python tutorials and tips | Python theme month
  • Python keywords, identifiers, and variables | Python theme month
  • Python statements, expressions, and indentation | Python theme month
  • How to write comments and multi-line comments in Python | Python Theme Month
  • Python data types — Basic to advanced learning | Python topic month
  • Python’s powerful functions: Map (), Filter (), and Reduce () | Python theme month
  • 100 Basic Python Interview Questions Part 1 (1-20) | Python topic month
  • 100 Basic Python Interview Questions Part 2 (21-40) | Python topic month
  • 100 Basic Python Interview Questions Part 3 (41-60) | Python topic month
  • 100 Basic Python Interview Questions Part 4 (61-80) | Python topic month
  • 100 Basic Python Interview Questions Part 5 (81-100) | Python topic month

Recommended articles of the past:

  • Teach you to use Java to make a gobang game
  • Interesting way to talk about the history of JavaScript โŒ›
  • The output of a Java program | Java exercises ใ€‘ ใ€ 7 sets (including parsing)
  • โค๏ธ5 VS Code extensions that make refactoring easy โค๏ธ
  • It is said that if you have light in your eyes, everywhere you go is light
  • 140000 | 400 multichannel JavaScript ๐ŸŽ“ interview questions with answers ๐ŸŒ  items (the fifth part 371-424)

If you do learn something new from this post, like it, bookmark it and share it with your friends. ๐Ÿค— Finally, don’t forget โค or ๐Ÿ“‘ for support