python Basic Tutorial: Python nested skills to use if and else statements in a for loop

Python's syntactic sugar is very strong, such as Python nested skills to use if and else statements in a for loop is to force it, let's just look at a few examples detailed usage:
for ... [if] ... build List (List comprehensions)
1. simple for ... [if] ... statement
in Python, for ... [if] statement ... List of constructing a simple method, from the List for a given selected elements satisfies condition if new List wherein if it may be omitted. Below a few simple examples will be described

>>> 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]

After if omitted, newList List constructed with the same elements and a. However, newList and a different List. Performing b = a, b are different and newList. is selected to satisfy newList2 List x% 2 == 0 elements from a composition of the. If not used for ... [if] ... statements, the following operations need to construct newList2.

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

Obviously, using for ... [if] ... statement is less verbose.

2. Nested for ... [if] ... statements
nested for ... [if] ... statement that satisfies the condition if an element composed from a plurality of new List List. Here also a few 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 and multiple statement for quite foremost for the statement is the outermost loop.

Python make good use of the else clause
in everyday coding, a branch statement is very common, often some control over code execution logic depending on whether certain conditions are satisfied, so we must be familiar with if [elif [else]] . Branch statement in the else clause is executed to when other conditions are not met, the appropriate use branching statements allow us to be more abundant in the code logic.
Use else clause used in common programming language in substantially the same branch statement, similar to that provided a default path of execution, if with the use of other conditional statement, compared to other programming languages (c #, java, js etc.) in python, else there are some special usage, with for, while the use of loops, etc., and even with exception handling carried out using try except statement can make our code more concise.

1. fit for / while loop used
later in the for loop statement else clause Then, when the end of the normal cycle (the case of a non-return or break in an early exit like), else clause logic is executed to . 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 number
3 it's a prime number
5 it's a prime number

A simple example of printing prime numbers, to determine whether a number is prime time needed to traverse smaller than its own integer, in any case a meet divisible by the judge ends, otherwise print this is info a prime number, with else's blessing, whole an example of the logic equivalent to "self-expressive", as the pseudo-code is generally a good understanding and comparison sets the flag value at the time of determination divisible then judgment flag value determination message primes whether numbers printed at the end of the function, the code more not so much concise description of how to do a "procedural" ready to work.
ps: We can compare the annotated code running under the effect of the example.

2. The error control with the except try to use
the exception handling statement, else similar usage, when the try block without throwing exceptions, else to a block of statements is 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:

123
convert 123 to integer successfully
cannot convert me123 to a integer

As print journal, in practical use the wrong time of the conversion success did not occur, else statement will be executed in the logic, of course, this example may not have much of anything, but was able to explain else useful in the treatment of error : simplified logic, avoiding the use of some of the flags value will be able to accurately grasp the situation if an error occurs to do some actual operation (such as when an error occurs if the stored data, the operation rollback in the else block, and then also followed plus finally statement to complete some cleanup operations.
thank you very much reading
of the University of time to choose a self-python, found that eating a working computer basic bad loss, this is not educated
can not do, can only be acquired to make up, so in outside the coding opened his own counter-attack the road, constantly learning python core knowledge, in-depth knowledge of basic computer learning, organized, if you are unwilling to mediocrity, it is with me outside of coding, growing it!
in fact, there is not only technical, more technical stuff than those, for example, how to make a fine Programmer, rather than the "Cock wire", the programmer itself is a noble presence, ah, is not it? [Click to join] want you want to be a noble person, come on!

Published 14 original articles · won praise 2 · Views 6670

Guess you like

Origin blog.csdn.net/chengxun03/article/details/105397907