[转]30 ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[转]30 ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS相关的知识,希望对你有一定的参考价值。

If you ask any Python programmer to tell about the strengths of Python, he will quote brevity and high readability as the most influencing ones. In this Python tutorial, we’ll cover many essential Python tips and tricks that will authenticate the above two points.

We’ve been collecting these useful shortcuts (tips & tricks) since we started using Python. And what’s best than sharing something we know and which could benefit others as well.

In the past, we’d shared a list of Python programming tips for beginners that aimed to optimize code and reduce coding efforts. And our readers still enjoy reading it.

So today, we’re back with one more set of essential Python tips and tricks. All these tips can help you minify the code and optimize execution. Moreover, you can readily use them in live projects while working on assignments.

Each trick has an example given with a brief explanation. For testing the coding snippets, you can look up these online virtual terminals for Python code execution.

30 ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS.

TIPS#1. IN-PLACE SWAPPING OF TWO NUMBERS.

Python provides an intuitive way to do assignments and swapping in one line. Please refer the below example.

 

 

The assignment on the right seeds a new tuple. While the left one instantly unpacks that (unreferenced) tuple to the names <a> and <b>.

Once the assignment is through, the new tuple gets unreferenced and flagged for garbage collection. The swapping of variables also occurs at eventually.

 

TIPS#2. CHAINING OF COMPARISON OPERATORS.

Aggregation of comparison operators is another trick that can come handy at times.

 

 

 

TIPS#3. USING TERNARY OPERATOR FOR CONDITIONAL ASSIGNMENT.

Ternary operators are a shortcut for an if-else statement and also known as conditional operators.

 

 

Here are a few examples which you can use to make your code compact and concise.

The below statement is doing the same what it is meant to i.e. “assign 10 to x if y is 9, otherwise assign 20 to x“. We can though extend the chaining of operators if required.




 

 

Likewise, we can do the same for class objects.

 

 

In the above example, classA and classB are two classes and one of the class constructors would get called.

Below is one more example with a no. of conditions joining to evaluate the smallest number.

 

 

We can even use a ternary operator with the list comprehension.

 

 

 

TIPS#4. MULTI-LINE STRINGS.

The basic approach is to use backslashes which derive itself from C language.

 

 

One more trick is to use the triple-quotes.

 

 

The common issue with the above methods is the lack of proper indentation. If we try to indent, it’ll insert whitespaces in the string.

So the final solution is to split the string into multi lines and enclose the entire string in parenthesis.

 

 

 

TIPS#5. STORING ELEMENTS OF A LIST INTO NEW VARIABLES.

We can use a list to initialize a no. of variables. While unpacking the list, the count of variables shouldn’t exceed the no. of elements in the list.

 

 

 

TIPS#6. PRINTING THE FILE PATH OF IMPORTED MODULES.

If you want to know the absolute location of modules imported in your code, then use the below trick.

 

 

 

TIPS#7. INTERACTIVE “_”.

It’s a useful feature which not many of us are aware.

In the Python console, whenever we test an expression or call a function, the result dispatches to a temporary name, _ (an underscore).

 

 

The “_” references to the output of the last executed expression.

 

TIPS#8. DICTIONARY/SET COMPREHENSIONS.

Like we use list comprehensions, we can also use dictionary/set comprehensions. They are simple to use and just as effective. Here is an example.

 

 

Note- There is only a difference of <:> in the two statements. Also, to run the above code in Python3, replace <xrange> with <range>.

 

TIPS#9. DEBUGGING SCRIPTS.

We can set breakpoints in our Python script with the help of the <pdb> module. Please follow the below example.

 

 

We can specify <pdb.set_trace()> anywhere in the script and set a breakpoint there. It’s extremely convenient.

 

TIPS#10. SETUP FILE SHARING.

Python allows running an HTTP server which you can use to share files from the server root directory. Below are the commands to start the server.

# PYTHON 2

 

 

# PYTHON 3

 

 

Above commands would start a server on the default port i.e. 8000. You can also use a custom port by passing it as the last argument to the above commands.

 

TIPS#11. INSPECT AN OBJECT IN PYTHON.

We can inspect objects in Python by calling the dir() method. Here is a simple example.

 

 

 

 

TIPS#12. SIMPLIFY IF STATEMENT.

To verify multiple values, we can do in the following manner.

 

 

instead of:

 

 

Alternatively, we can use ‘{1,3,5,7}’ instead of ‘[1,3,5,7]’ for ‘in’ operator because ‘set’ can access each element by O(1).

 

TIPS#13. DETECT PYTHON VERSION AT RUNTIME.

Sometimes we may not want to execute our program if the Python engine currently running is less than the supported version. To achieve this, you can use the below coding snippet. It also prints the currently used Python version in a readable format.

 

 

Alternatively, you can use sys.version_info >= (3, 5) to replace sys.hexversion != 50660080 in the above code. It was a suggestion from one of the informed reader.

Output when running on Python 2.7.

 

 

Output when running on Python 3.5.

 

 

 

TIPS#14. COMBINING MULTIPLE STRINGS.

If you want to concatenate all the tokens available in a list, then see the below example.

 

 

Now, let’s create a single string from the elements in the list given above.

 

 

 

TIPS#15. VERSATILE REVERSE MECHANISM.

# REVERSE THE LIST ITSELF.

 

 

# REVERSE WHILE ITERATING IN A LOOP.

 

 

# REVERSE A STRING IN LINE.

 

 

This gives the output as ”nohtyP tseT”

# REVERSE A LIST USING SLICING.

 

 

The above command will give the output as [5, 3, 1].

 

TIPS#16. PLAY WITH ENUMERATION.

With enumerators, it’s easy to find an index while you’re inside a loop.

 

 

 

TIPS#17. USING ENUMS IN PYTHON.

We can use the following approach to create enum definitions.

 

 

 

TIPS#18. RETURNING MULTIPLE VALUES FROM FUNCTIONS.

Not many programming languages support this feature. However, functions in Python do return multiple values.

Please refer the below example to see it working.

 

 

 

TIPS#19. UNPACK FUNCTION ARGUMENTS USING SPLAT OPERATOR.

The splat operator offers an artistic way to unpack arguments lists. Please refer the below example for clarity.

 

 

 

TIPS#20. USE A DICTIONARY TO STORE A SWITCH.

We can make a dictionary store expressions.

 

 

 

TIPS#21. CALCULATE THE FACTORIAL OF ANY NUMBER IN ONE LINE.

PYTHON 2.X.

 

 

PYTHON 3.X.

 

 

 

TIPS#22. FIND THE MOST FREQUENT ELEMENT IN A LIST.

 

 

 

TIPS#23. RESETTING THE RECURSION LIMIT.

Python restricts recursion limit to 1000. We can though reset its value.

 

 

Please apply the above trick only if you need it.

 

TIPS#24. CHECK THE MEMORY USAGE OF AN OBJECT.

In Python 2.7, a 32-bit integer consumes 24-bytes whereas it utilizes 28-bytes in Python 3.5. To verify the memory usage, we can call the <getsizeof> method.

IN PYTHON 2.7.

 

 

IN PYTHON 3.5.

 

 

 

TIPS#25. USE __SLOTS__ TO REDUCE MEMORY OVERHEADS.

Have you ever observed your Python application consuming a lot of resources especially memory? Here is one trick which uses <__slots__> class variable to reduce memory overhead to some extent.

 

 

Clearly, you can see from the results that there are savings in memory usage. But you should use __slots__ when the memory overhead of a class is unnecessarily large. Do it only after profiling the application. Otherwise, you’ll make the code difficult to change and with no real benefit.

 

TIPS#26. USING LAMBDA TO HANDLE PRINTING.

 

 

 

TIPS#27. CREATE DICTIONARY FROM TWO RELATED SEQUENCES.

 

 

 

TIPS#28. IN LINE SEARCH FOR MULTIPLE PREFIXES IN A STRING.

 

 

 

TIPS#29. FORM A UNIFIED LIST WITHOUT USING ANY LOOPS.

 

 

 

TIPS#30. IMPLEMENTING A TRUE SWITCH-CASE STATEMENT IN PYTHON.

Here is the code that uses a dictionary to imitate a switch-case construct.

 

 

 

SUMMARY – ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS.

We wish the essential Python tips and tricks given above would help you do the tasks quickly & efficiently. And you could use them for your assignments and projects.

Listening to your feedback makes us do better so share it.

You can even ask us to write on a topic of your choice. We’ll add it to our writing roadmap.

Lastly, if you’d enjoyed the post, then please care to share it with friends and on social media.

Keep Learning,

TechBeamers.

以上是关于[转]30 ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS的主要内容,如果未能解决你的问题,请参考以下文章

转TI Z-stack协议栈学习-添加新任务

如何使用 xamarin essential 确定网络类型是 2g、3g 还是 4g

Ti-Calculator 上的多语言编程

TI德州芯片TLV系列和TPS系列芯片区别(转)

玩转华为ENSP模拟器系列 | 配置SR-MPLS BE隧道的TI-LFA FRR功能示例

python中如何把string 转换成int