Python uses the if and else statements nested in the for loop, pythonelse

Source: Internet
Author: User

Python uses the if and else statements nested in the for loop, pythonelse

For... [if]... construct List (List comprehension)
1. Simple for... [if]... statement
In Python,... [if]... statement is a simple method to construct a List. From the List given by for, select the elements that meet the if condition to form a new List, where if can be omitted. The following are some simple examples.

>>> a=[12, 3, 4, 6, 7, 13, 21]>>> newList = [x for x in a]>>> newList[12, 3, 4, 6, 7, 13, 21]>>> newList2 = [x for x in a if x%2==0]>>> newList2[12, 4, 6]

If is omitted, newList constructs a List with the same elements as. However, newList and a are different lists. Execute B = a, B and newList. NewList2 is a List composed of x % 2 = 0 elements selected from. If you do not use the for... [if]... statement, the following operations are required to build newList2.

>>> newList2=[]>>> for x in a:...  if x %2 == 0:...    newList2.append(x)>>> newList2[12, 4, 6]

Obviously, the statement for... [if]... is more concise.

2. nested for... [if]... statement
Nested for... [if]... statements can select elements that meet the if condition from multiple lists to form a new List. The following are examples.

>>>a=[12, 3, 4, 6, 7, 13, 21]>>>b=['a', 'b', 'x']>>>newList=[(x, y) for x in a for y in b]>>>newList[(12, 'a'), (12, 'b'), (12, 'x'), (3, 'a'), (3, 'b'), (3, 'x'), (4, 'a'), (4, 'b'), (4, 'x'), (6, 'a'), (6, 'b'), (6, 'x'), (7, 'a'), (7, 'b'), (7, 'x'), (13, 'a'), (13, 'b'), (13, 'x'), (21, 'a'), (21, 'b'), (21, 'x')]>>>newList2=[(x, y) for x in a for y in b if x%2==0 and y<'x']>>>newList2[(12, 'a'), (12, 'b'), (4, 'a'), (4, 'b'), (6, 'a'), (6, 'b')]

Nested for... [if]... statements are equivalent to multiple for statements. The first for statement is the outermost loop.

Use the else clause of python
In daily coding, the use of branch statements is very common. It is often used to control the logic of code execution based on whether certain conditions are met, therefore, you will not be unfamiliar with if [elif [else. When other conditions are not met, the else clause in the branch statement will be executed. The proper use of the branch statement can enrich our code logic.
The use of else clauses in branch statements is basically the same in some common programming languages. It is similar to providing a default execution path, which can be used together with the if and other condition judgment statements, compared with other programming languages (c #, java, js, etc.), else has some special usage in python, which can be used with loop statements such as for and while, it can even be used with the try again t statement for exception handling to make our code more concise.

1. Use with the for/while LOOP statement
After the for loop statement is followed by the else clause, the logic of the else clause is executed when the loop ends normally (when the return or break clause exits early. 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:         # found = False         break    else:      print "{} it's a prime number".format(i)    # if found:         # print "{} it's a prime number".format(i)
print_prime(7)

Result:

2 it's a prime number3 it's a prime number5 it's a prime number

An example of simply printing a prime number is used to determine whether a number is a prime number and traverse an integer smaller than itself. If any number satisfies the division, it is deemed to end, otherwise, the info of the prime number is printed. With the else blessing, the logic of the entire example is equivalent to "self-expressive ", like pseudo code, it is better to understand and set the flag value when determining the division, and then judge the flag value at the end of the function to determine whether to print messages with prime numbers, the code is more concise than so much to describe how to do the "procedural" preparation work.
Ps: You can compare the running effect of the annotated code in the example.

2. Use with try deny t Error Control
In exception handling statements, else has similar usage. When the try code block does not throw any exception, the else statement block will be executed.

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")
Result:
123convert 123 to integer successfullycannot convert me123 to a integer

As shown in the print log, the logic in the else statement will be executed when the conversion is successful without an error. Of course, this example may not be of much practical use, however, else is useful in error handling: simplifying the logic, avoid using some flag values to accurately determine whether an error occurs and perform some actual operations. For example, if an error occurs during data storage, perform rollback operations in the else statement block, then you can add finally statements to complete some cleanup operations.

The use of else statement blocks allows us to write code that is more concise and closer to the semantics of natural languages. Of course, it will be more pythonic, and you can learn more about the nuances.

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.