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