Sentence Optimization and skills of python
This article mainly explains "Python sentence optimization and skills", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "Python sentence optimization and skills"!
1. or and
In an if conditional statement, for an or expression, the variable with a higher probability of being true should be written before or, while and should be delayed.
2. Use type less when checking the type of an object
To use isinstance, check if int is of type int isinstance(num,int) returns true.
3.eval is evil
eval is an expression that treats strings as valid expressions. But there are security holes.
if that object you are use is not a trust source, you should avoid using eval and use ast.literal_eval instead.
4. Use enumerate() to get the index and value of a sequence iteration
enumerate(iterable object, starting subscript default 0)
5. i +=1 is not equal to ++i
In Python ++i is actually +(+i), where + represents a positive sign.
6. For…else for i in rang(4):
if i==4:
break
else:
print("else is run")
If the for loop ends with a break then else does not print, if the for loop ends naturally then else will print.
7.Avoid adding return statement def test(a) in finally statement:
try:
if a