Python More control Flow tool (i)

Source: Internet
Author: User

4.1.ifStatements

Perhaps the most well-known statement type is the if statement. For example:

The IF statement is probably the most common control flow statement, for example:

>>> x =int(Input ("Please enter an integer:")) Please enter an integer: the>>>ifX <0: ... x=0... print ('negative changed to zero') ... elif x==0:... Print ('Zero') ... elif x==1:... Print (' Single')... Else:... Print (' More')... more

There can be zero or more elif parts, and the else part is optional. The keyword 'elif' are short for ' else if ', and are useful to avoid excessive indentation. An if ... elif ... elif sequence is a substitute for the switch or case statements found in other languages.

There can be 0 or more elif parts, and the Else section is optional. The keyword Elif is the else if abbreviation, which can effectively avoid excessive indentation. If...elif...elif can make switch...case statements in other languages. (Python does not have a switch statement).

4.2. forStatements

The for statement in Python differs a bit from "What is May is used to C or Pascal." Rather than iterating over an arithmetic progression of numbers (as in Pascal), or giving the user the ability to Define both the iteration step and halting condition (as C), Python ' s for statement iterates over the items of a NY sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):

In Python, the For statement is a little different from the C or Pascal language you use, in the Pascal language, the For statement is always iterated over a number of arithmetic progression, and in c the user can define the loop condition and the step difference. In Python, a for statement iterates through each element of a sequence. For example:

>>>= ['cat'window '  Defenestrate'] for in words:      ... 3  6

  If you want to modify a sequence at the same time as an iteration (such as copying an element), it is recommended that you copy the sequence first. Because iterating a sequence does not implicitly copy the sequence. The following slicing operations are very handy for copying sequences:

 >>> for  w in   words[:]: # Loop over a slice copy of the entire list ....  if  Len (w) > 6  : Words.insert ( 0  , W) ...  >>> words[ "  defenestrate  , "  cat  , "   ,    Defenestrate  ] 

4.3. TheRange ()Function

If you don't need to iterate through a sequence of numbers, the built-in function range () comes in handy. It generates arithmetic progressions:

If you need a variable sequence of numbers, then the built-in function rang () comes in handy. It will produce a sequence.

 for  in range (5): ...     Print (i) ... 0 1 2 3 4

The given end point was never part of the generated sequence; range generates values, the legal indices for items of a sequence of length 10. It is possible-let the range start at another number, or to specify a different increment (even negative; sometimes thi S is called the ' Step '):

The range () function is also subject to the pre-closing principle; Range (10) produces 10 values (0 to 9), you can specify the starting value of the numeric sequence, or specify a different step difference (the step difference can be a negative number)

Range (5   )59range (03 )   0369Range (-ten,100 ,-+)  -ten,--

To iterate through the indices of a sequence, you can combine range () and Len () as follows:

You can iterate by index sequence, and you can combine the range () and Len () functions:

>>> a = ['Mary','had','a','Little','Lamb']>>> forIinchRange (len (a)): ... print (i, a[i]) ...0Mary1had2a3Little4Lamb

In most such cases, however, it's convenient to use the enumerate () function, see looping techniques.

In more cases, it would be easier to use the enumerate () function, see looping techniques

A strange thing happens if you just print a range:

If you print the Rang () function directly with the print () function, you will see a strange phenomenon:

>>> print (range)range (0)

In many ways the object returned by range () behaves as if it's a list, but in fact it isn ' t. It is a object which returns the successive items of the desired sequence when you iterate over it, but it doesn ' t really Make the list, thus saving space.

We may think that rang () should return a list-like object, but it is not. When you iterate over it, it returns the sequential elements of the desired sequence, but it is not a list, which is to save space.

We say such an object are iterable, that's, suitable as a target for functions and constructs that expect Somethi Ng from which they can obtain successive items until the supply is exhausted. We have seen, the for statement are such an iterator. The function list () is another; It creates lists from Iterables:

We call this object: An iterative iterable, and we've actually seen the for statement as a iterator. The function list () also returns a list with the iteration object as a parameter:

>>> list (range (5)) [01234]

Later we'll see more functions this return iterables and take iterables as argument.

Below, we'll see more functions returning an iterative object or iterating over an object as an argument.

4.4. BreakandContinuestatements, andElseClauses on Loops

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

Loop statements May has an else clause; It is executed when the loop terminates through exhaustion of a list (with a) or when the condition becomes F Alse (with while), but not when the loop was terminated by a breaks statement. This was exemplified by the following loop, which searches for prime numbers:

Like the C language program, the break statement is used to jump out of the nearest for or while loop.

A looping statement can have an ELSE clause, and an else statement is executed when the loop jumps out of the loop condition. However, if you jump out of the loop through a break, the else statement is not executed. Look at the following example to search for prime numbers:

>>> forNinchRange2,Ten):...      forXinchRange2, N): ...ifn% x = =0:... print (n,'equals'X'*'N//x)... Break...     Else:... # loop fell through without finding a factor ... print (n,'Is a prime number')...2  isa prime number3  isa prime number4equals2*25  isa prime number6equals2*37  isa prime number8equals2*49equals3*3

(Yes, this is the correct code.) Look closely:the Else clause belongs to the for loop, not the if statement.)

(yes, this is the correct code, look closely, the ELSE clause belongs to the inside for loop, not the IF statement)

When used with a loop, the else clause have more in common with the else clause of a try stateme NT than it does that's if statements:a try statement ' s else clause runs when no exception OCC Urs, and a loop ' s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.

Else clause the most common use of another application is with the Try statement: When no exception occurs, the ELSE clause to the TRY statement is used. For more try statements and exceptions, consult exception handling.

4.5.PassStatements

The pass statement does nothing. It can be used if a statement is required syntactically and the program requires no action. For example:

Pass statement function: Do not do anything. It is usually used when a statement needs to contain a statement, but does not need to do anything. For example:

 while True:     ... Pass  # Busyfor keyboard interrupt (CTRL +C) ...

This is commonly used for creating minimal classes:

The most common use is to create the simplest class:

class Myemptyclass:     ... Pass ...

Another place pass can being used is as a place-holder for a function or conditional body if you were working on NE W code, allowing keep thinking at a more abstract level. The pass is silently ignored:

Another place to use pass is: When you write new code, give the function or condition body a placeholder, allowing you to keep the function running or more abstract. Pass statements are ignored directly:

>>> def initlog (*args): ...     Pass   this! ...

Python More control Flow tool (i)

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.