Translation of Writing idiomatic Python (a): If statement, for loop

Source: Internet
Author: User

The opening crap.

This is a very good book on Amazon in the United States, in fact, strictly speaking, this may not be a book, but a booklet. Like the title of the book, the content is mainly about how the native Python code is written in some examples. In the book, many examples are contrasted with bad style and idiomatic python, but the content is not completely covered, but each one is very representative. Overall is very suitable for the novice, while some of the entry veteran saw may also have the feeling of enlightened. Author Jeff Knupp has developed financial systems in the world's most bull-B Goldman Sachs and other banks, and has been active in the North American Python community.

Python has been used for some years, and has done business development for more than a year, but most of the others are based on research and pre-research algorithms. Recently because began to use Python to do commercial development, so think about the way to find some books to see, inadvertently saw this small book, feel very good, not to sell at home, not to mention the Chinese version. Translation This book, is to review and re-think of Python, but also have a small number of their own views (C + + style comment Green bold ), I hope to adhere to it. The version I'm looking at is mainly divided into four parts: controlStructures and Functions(controlling structure and function),workingwith data (datatype and type),organizing YourCode (organization of Codes), GeneralAdvice(generic recommendation). Each part is divided into different small chapters, altogether more than 20. I will release an indefinite number of chapters in this order. My English proficiency, but no translation experience, although I do not know if anyone will pay attention to this series, or hope that if there is a crossing, please take a light:)

1. Control structure and function 1.1 If statement 1.1.1 make statements more concise by chaining comparisons

When using the IF statement, using a chain-like comparison operation will not only make the statement more concise, but also make the execution more efficient.

Bad style:

1 if x <= y and y <= z:2     return True

Authentic Python:

1 if x <= y <= z:2     return True

Python explains how to perform these two different comparison methods, in fact, are compared x<=y first, if true, then compare Y<=z. The main difference is that when the chain comparison, the value of Y will be taken first, and then copy the pressure stack, the whole process of the evaluation of Y only executed once, and in the way of and, Y's evaluation will be executed two times, that is, if the comparison is three functions or complex objects, the chain comparison will only be evaluated three times, The method that is compared by and is evaluated 4 times. This is probably why the authors say that execution is more efficient, but in fact it is not likely that efficiency will improve if it is simply a comparison of variables.

1.1.2 Avoid placing code and colons on the same line in a conditional branch

Using indentation to represent the structure of a block of code makes it easier to judge the code structure of a conditional branch. if,elif and else statements should always have a single line, no code after the colon.

Bad style:

1 name = ' Jeff ' 2 address = ' New York, NY ' 3 4 if Name:print (name) 5 print (address)

Authentic Python:

1 name = ' Jeff ' 2 address = ' New York, NY ' 3 4 if Name:5     print (name) 6 print (address)

The code in the file should follow this rule, and a line in the console would be

1.1.3 Avoid repeated occurrences of the same variable name in a compound if statement

When you want to use the IF statement to check if a variable is equal to a number of values, a check that repeats multiple times with = = and or is equal is a lengthy code. The simple notation is to determine whether the variable is in a structure that can be traversed.

Bad style:

1 is_generic_name = False2 name = ' Tom ' 3 if name = = ' Tom ' or ' name = = ' Dick ' or ' name = = ' Harry ': 4     is_generic_name = Tru E

Authentic Python:

1 name = ' Tom ' 2 is_generic_name = name in (' Tom ', ' Dick ', ' Harry ')
1.1.4 Avoid direct comparisons with true, false or None

For an object in any Python, whether it is built-in or user-defined, it is inherently associated with an internal "truth" (truthiness). So naturally, when judging whether a condition is true, try to rely on the implicit "truth" in the conditional Judgment statement. The following is a case where "truth" is false:

Value 0
Empty sequence (list, tuple, etc.)
An empty Dictionary
The 0 value returned when __len__ or __nonzero__ is called or false

In the last article above, we can also define the "true value" of the type we create by checking how the values returned after __len__ or __nonzero__ are called. In addition to those listed above, other cases are considered Truefor "truth".

The IF statement implicitly uses "truth" in Python, so you should do the same in your code. For example, the following is the wording:

if foo = = True:

The simpler and more straightforward notation is:

If foo:

There are many reasons to do so. The most obvious reason is that if your code changes, such as when Foo becomes an int instead of True or False, the IF statement is still correct when judging whether it is 0. On a deeper level, this is based on the difference between equality (equality) and equivalence (identity). Using = = checks whether two objects have equal or equivalent values (as defined by the _eq property), while the is statement examines whether two objects are the same object at the bottom.

The implementation of Python for equality is implemented in C code to convert the comparison object to a long type by Pyint_as_long, and then to compare it with the = = in C, while the IS implementation is a direct = = comparison.

So for False,None and null sequences such as [], {}, and () should avoid direct comparisons. If a list called My_list is empty, the if My_list is judged to be False. Of course there are cases, although not recommended, but the direct and None comparison is necessary. When you need to determine whether a parameter with the default value of None is assigned in a function, such as:

1 def insert_value (value, Position=none): 2     "" Inserts a value into the custom container, inserts     the position of the value 3 as an optional parameter, and the default value is None "" "4     if position is Not none:5 ...         

If you use if position: then where is the error? Imagine if someone wanted to insert a value in a 0-bit position, then the function would assume that the position parameter was not set because if0: would be judged to be False. Note that this is a not, according to PEP8, and None should always be compared to is or not rather than = =

In short, let Python's "truth" replace your work of comparison.

Bad style:

1 def number_of_evil_robots_attacking (): 2     return 3      4 def should_raise_shields (): 5     # Only open the shield when more than one giant robot is attacking 6     # so I just need to return the number of giant robots, if not zero will be automatically judged true 7     return number_of_evil_robots_attacking () 8  9 If should_raise_shields () = = True:10     raise_shields ()     print (' Shield turned on ')-else:13     print (' Safe! There's no giant robot attacking ')

Authentic Python:

1 def number_of_evil_robots_attacking (): 2     return 3      4 def should_raise_shields (): 5     # Only open the shield when more than one giant robot is attacking 6     # so I just need to return the number of giant robots, if not zero will automatically be judged true 7     return number_of_evil_robots_attacking () 8  9 If Should_raise_shields ():     raise_shields () one     print (' Shield turned on ') else:13     print (' Safe! There's no giant robot attacking ')
1.1.5 using if and else as an alternative to ternary operators

Unlike many other languages, Python has no ternary operators (for example, X-True:false). However, Python can defer assignment to conditional judgment, so ternary operations in Python can be replaced by conditional judgments. Of course, it is important to note that, unless it is a very simple statement, the alternative to ternary operations makes the statement less readable.

Bad style:

1 foo = True2 value = 4 if foo:5     value = 7 print (value)

Authentic Python:

1 foo = True2 3 value = 1 if foo else 5 print (value)
1.2 For Loop 1.2.1 Use the enumerate function in a loop to create a count or index

In many other languages, developers are accustomed to explicitly declaring a variable to be used as a count in a loop or as an index to a related container. For example, in C + +:

1 for (int i = 0, I < container.size (); ++i) 2 {3     //Do STUFF4}

In Python, the built-in enumerate function is a natural way to handle this need.

Bad style:

1 My_container = [' Larry ', ' Moe ', ' Curly ']2 index = for element in My_container:4     print (' {} {} '. Format (index, Eleme NT)) 5     Index + = 1

Authentic Python:

1 My_container = [' Larry ', ' Moe ', ' Curly ']2 for index, element in enumerate (My_container): 3     print (' {} {} '. Format (Inde x, Element))
1.2.2 iterating through an iterative structure using the IN keyword

In languages without For_each style, developers are accustomed to using indexes (subscripts) to traverse elements in a container. In Python, this can be done more gracefully with the In keyword.

Bad style:

1 my_list = [' Larry ', ' Moe ', ' Curly ']2 index = while index < Len (my_list): 4     print (My_list[index]) 5     Index + = 1

Authentic Python:

1 my_list = [' Larry ', ' Moe ', ' Curly ']2 for element in My_list:3     print (Element)
1.2.3 use else to execute a for loop after all the end of the code

In the Python for loop, you can include an else clause, which is a technique that few people know. The Else statement block executes after the end of the iteration in the For loop, unless it loops during the iteration because the break statement ends. Using this notation, we can perform conditional checks in loops. Either stop the loop with the break statement when the conditional statement you want to check is true, or go to the else statement block after the loop ends and perform the action if the condition is not met. This avoids the use of a single indicator variable in the loop to check whether the condition is satisfied.

Bad style:

1 for user in Get_all_users (): 2     has_malformed_email_address = False 3     print (' Check {} '. Format (user)) 4 for     Emai L_address in User.get_all_email_addresses (): 5         if Email_is_malformed (email_address): 6             Has_malformed_email_ Address = True 7             print (' contains a malicious email address! ') 8 break             9     if not has_malformed_email_address:10         print (' All email addresses are valid! ')

Authentic Python:

1 for user in Get_all_users (): 2     print (' Check {} '. Format (user)) 3 for     email_address in User.get_all_email_ Addresses (): 4         if Email_is_malformed (email_address): 5             print (' contains a malicious email address! ') 6             break7     else:8         print (' All email addresses are valid! ')

Translation of Writing idiomatic Python (a): If statement, for loop

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.