In addition to the [while] statement introduced earlier, Python has borrowed and changed some of the flow-control features from other languages.

4.1. [if] statement

Perhaps the most famous is the [if] statement. Such as:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...      x = 0
...      print('Negative changed to zero')
... elif x == 0:
...      print('Zero')
... elif x == 1:
...      print('Single')
... else:
...      print('More')
...
More

There may be zero to more [elif] sections, and [else] is optional. The keyword ‘[elif]’ is short for ‘else if’, which is a good way to avoid deep indentation. [if]… [elif]… [elif]… Sequences are used in place of switch or case statements in other languages.

4.2. [for] statement

The [for] statement in Python is slightly different from that in C or Pascal. A normal loop might be based on an arithmetic numerical step (as in Pascal), or the user defines the iteration step and the termination condition (as in C). Python’s [for] statement iterates according to the children of any sequence (a linked list or a string) in the order in which they are in the sequence. (no implied, for example) : so students want to learn, it is necessary to listen to the teacher’s class, get the python welfare, want to learn the students can go to the dream child teacher wai xin (homonyms) : front row is: 762, in the middle of a row is: 459, the back of a set of is: 510, the above three group of letters can be combined in accordance with the order, she will be learning arrangements.

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

It is not safe to modify an iterative sequence during an iteration (this is only true if you are using a mutable sequence such as a linked list). If you want to modify the sequence you’re iterating over (for example, the copy selection), you can iterate over its copy. This can be done conveniently with a cut sign:

>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

4.3 the range () “function

If you need a sequence of numbers, the built-in function [range()] comes in handy, it generates a list of arithmetic series:

>>> for i in range(5): ... print(i) ... 0, 1, 2, 3, 4

Range (10) generates a list of 10 values. It populates the list of length 10 with the index values of the list. The resulting list does not include the end values of the range. Also can let [range ()] operation from another value, or you can specify a different step values (and even negative, sometimes it is also known as “step”) : so the students want to learn, it is necessary to listen to the teacher’s class, get the python welfare, want to learn the students can go to the dream child teacher wai xin (homonyms) : front row is: 762, the middle row is 459, the back row is 510, put the above three groups of letters together in order, she will arrange the study.

range(5, 10)
   5 through 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70

To iterate over the list index, use the combination of [range()] and [len()] as follows

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

However, a handy way to do this is to use [enumerate()], see the looping technique.

A strange thing happens if you just print a sequence:

>>> print(range(10))
range(0, 10)

In various ways the object returned by the [range()] function behaves as if it were a list, but in fact it is not. When you iterate over it, it’s an object that returns a sequence of items like the desired sequence; But to save space, it doesn’t actually construct the list.

We call such objects iterable, that is, suitable as a target (argument) for functions or structures that expect to get a continuous term from something to the end. The [for] statement we’ve seen is one such iterator. The [list()] function is another (iterator) that creates lists from iterable (objects) :

>>> list(range(5))
[0, 1, 2, 3, 4]

We’ll see more functions that return iterables and take iterables as arguments later.

4.4. [break] and [continue] statements, and [else] clauses in loops

The [break] statement, similar to that in C, is used to break out of the nearest [for] or [while] loop.

Loops can have an else clause; It is executed if the loop iterates through the list (for [for]) or if the condition is false (for [while]), but not if the loop is aborted by [break]. The following example program for searching for primes demonstrates this clause:

>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2  * 4 9 equals 3 * 3

(Yes, this is the correct code. Look carefully: the else statement belongs to the [for] loop, not the [if] statement.

When used with a loop, the else clause has more in common with the [try] else clause than with the [if] statement: the [try] else clause runs when no exception occurs, and the loop else clause runs when no break occurs. For more information about the [try] statement and exceptions, see exception Handling.

The [continue] statement is borrowed from C and indicates that the loop continues through the next iteration:

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

4.5. (pass) statement

The [pass] statement does nothing. It is used in cases where the syntax must be certain, but the program does nothing, such as:

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

This is usually used to create the least structured class:

>>> class MyEmptyClass:
...     pass
...

On the other hand, [pass] can be used as a placeholder for a function or control body when creating new code. It allows you to think at a more abstract level. 10. [pass] to be silently ignored:

>>> def initlog(*args): ... pass # Remember to implement this! .

If you do meet a good colleague, you’ll be lucky. Go ahead and learn.

Python, crawler skills to share resources added wei Xin (tongyin) :762459510

Python, PythonWeb, crawler, data analysis and other Python skills, as well as artificial intelligence, big data, data mining, office automation and other learning methods.

Build from zero foundation to project development start combat all-round analysis!