Python's Else Clause usage guide

Source: Internet
Author: User
In the daily coding, the use of branch statements is very common, often based on whether certain conditions to meet the logic of code execution some control, so everyone to If[elif[else]] must not be unfamiliar. The ELSE clause in the branch statement is executed when other conditions are not satisfied, and the appropriate use of the branch statement can enrich our code logic.

Using the ELSE clause in a branch statement is basically the same usage in some common programming languages, similar to providing a default execution path, using conditional judgment statements with if, and other programming languages (C #, Java, JS, etc.) in Python, else there are some special usages The use of loop statements with for and while, and even with exception handling try except statements, can make our code more concise.

Use with For/while loop statements

After the FOR Loop statement, the ELSE clause is followed, and the logic of the ELSE clause is executed at the end of the loop (in case of an early exit, such as a return or break). Let's look at an example:

def print_prime (n):  for I in xrange (2, N):    # found = True    for J in Xrange (2, i):      if I% j = = 0:         # Foun D = False         break    else:      print "{} It ' s a prime number". Format (i)    # if found:         # print "{} It's a prime n Umber ". Format (i) print_prime (7) 2 It's a prime number3 it ' s a prime number5 it's a prime number

An example of a simple print prime, to determine whether a number is a prime, you need to traverse a small integer than its own, any one satisfies the division of the end of the judgment, otherwise printing this is a prime of info, with the other's plus, the whole example of the logic of the equivalent "Self-expressive", The code is more concise and less descriptive about how to do the "procedural" preparations, as the pseudo-code generally understands and sets the flag value at the end of the function and then determines whether the value of the number is printed at the bottom of the functions.

PS: You can compare the results of the annotated code in the example.

Use with try except error control

In an exception-handling statement, else has a similar usage, and the ELSE statement block is executed when the try code block does not throw any exceptions.

def my_to_int (Str_param):  try:    print int (str_param)  except ValueError:    print ' cannot convert {} to a Integer '. Format (Str_param)  else:    print ' convert {} to integer successfully '. Format (str_param) My_to_int ("123 ") My_to_int (" me123 ") 123convert 123 to integers successfullycannot convert me123 to a integer

As shown in the print log, the logic in the ELSE statement will be executed when the conversion succeeds without error, although this example may not have much practical use, but it can roughly illustrate the usefulness of else in fault handling: simplifying logic, Avoid using some of the flag values to be able to accurately grasp whether the error occurred to do some practical operation (such as when the data is saved if an error occurs, in the ELSE statement block rollback operation, and then can be followed by a finally statement to complete some cleanup operations.

The use of the else block allows us to write code that is more concise, closer to the semantics of the natural language, and, of course, more pythonic, and the finer things can be learned slowly.

  • 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: info-contact@alibabacloud.com 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.