"Basic Python Tutorial" Reading notes fifth (next) circular statements

Source: Internet
Author: User

5.5.1while Cycle

X=1while x<=100:    print X    

Make sure the user has entered a name:

Name= "" And not Name:    name=raw_input (' Please enter your name: ') print ' hello,%s! ' %name

5.5.2for Cycle

The while statement is very flexible. It can be used to repeatedly execute a block of code in case any condition is true. In general, this is enough, but sometimes it has to be tailored. For example, you want to execute a block of code for each element of a collection (sequences and other objects that can iterate). You can use the For statement at this time:

Words=[' A ', ' B ', ' C ', ' d ']for word in words:    print Word

5.5.3 looping through a dictionary element

A simple for statement can loop through all the keys of a dictionary, just as it does with a sequence

d={' x ': 1, ' Y ': 2, ' z ': 3}for key in D:    print key, ' corresponds to ', D[key]

Note: The order of the dictionary elements is usually undefined. In other words, when iterating, the health and values in the dictionary are guaranteed to be processed, but the processing order is indeterminate. If the order is important, you can save the key values in a separate list, such as sorting before the iteration.

5.5.4 Some iterative tools

1. Parallel iterations

A program can iterate over two sequences at the same time.

names=[' Anne ', ' Beth ', ' George ', ' Damon ']ages=[12,45,32,102]for I in  range (len (names)):    print names[1], "is", Ages[i], ' years old '

The built-in zip function can be used for parallel iterations, which can "compress" the two sequences together and return a list of tuples:

>>> Zip (names,ages) [(' Anne ', '), (' Beth ', '), (' George ', ' + '), (' Damon ', 102)]

Unpacking tuples in loops:

>>> for name,age in Zip (names,ages):    print Name, "is", age, "years old" Anne is "years Oldbeth is" years OLDG Eorge is years Olddamon was 102 years old

The ZIP function can also be used for any number of sequences. The important thing about it is that the zip can handle unequal sequences: when the shortest sequence "runs out", it stops:

>>> Zip (Range (5), xrange (100000000)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

2. Numbering iterations

There are times when you want to iterate over an object in a sequence and also get the index of the current object. For example, replace all substrings containing ' XXX ' in a list of strings: \

Index=0for string in strings:    if ' xxx ' in strings:    strings[index]= ' [censored ' index+=1

Another approach is to use the built-in enumerate function:

3. Flipping and sorting iterations

Two useful functions: reversed and sorted: they are similar to the list's reverse and sort (sorted and sort use the same parameters), but on any sequence or iteration object, instead of modifying the object in place, it returns a flipped or sorted version:

>>> sorted ([4,3,5,8,1]) [1, 3, 4, 5, 8]>>> sorted (' hell,world! ')  ['! ', ', ', ' d ', ' e ', ' h ', ' l ', ' l ', ' l ', ' o ', ' R ', ' W ']>>> list (reversed (' Hello,world ') ') [' d ', ' l ', ' r ', ' O ', ' W ', ', ', ' o ', ' l ', ' l ', ' e ', ' H ']>>> '. Join (Reversed (' hello,world! ')) '! Dlrow,olleh '

5.5.5 jump out of the loop

1. Break

The break statement can be used to end (jump out) the loop.

From math import sqrtfor N in range (99,0,-1):    root=sqrt (n)    if root ==int (root):        print n        break

2. Continue

Continue will let the current iteration end, "Jump" to the beginning of the next round of loops. It basically means "skipping the rest of the loop body, but not ending the loop". This can be useful when the loop body is large and complex, and sometimes it is possible to skip it for some reason-this time use the Continue statement:

For x in SEQ:

If Condition1:continue

If Condition2:continue

If Condition3:continue

Do_something ()

Da_ Something_ Else ()

Do_ another_thing ()

ETC ()

Many times, you can use the IF statement as follows:

For x in SEQ:

If not (Condition1 or condition2 or Condition3)

Do_something ()

Do_something_else ()

Do_another_thing ()

ETC ()

3.while True/break Idioms

While True:    word=raw_input (' Please enter a word: ')    if not word:break    print ' The word was ' +word

The part of while true implements a loop that never stops itself. However, if a condition is added to the inside of the loop, the break statement is called when the condition is satisfied. This makes it possible to terminate the loop anywhere inside the loop rather than just at the beginning (like a normal while loop). The If/break statement naturally divides the loop into two parts: the 1th part is responsible for initializing (in the normal while loop, this part needs to be repeated), and the 2nd part uses the 1th part to initialize the good data when the loop condition is true.

The ELSE clause in the 5.5.6 loop

From math import sqrtfor N in range (99,81,-1):    root=sqrt (n)    if Root==int (root):        print n        break    Else :        print "didn ' t find it"

5.6 List derivation--lightweight loops

List comprehension is a way to create a new list (similar to a set deduction in mathematical terms) with other lists. It works like A For loop:

>>> [x*x for X in range (10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

You can add more parts of the FOR statement:

>>> [(x, Y) for x in range (3) for Y in range (3) [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), , 2)

5.7 Threesome:p for the guy, Del and exec

5.7.1 Pass

It can be used as a placeholder in the code. For example, the program needs a JF statement and then tests it, but lacks the code for one of the statement blocks, considering the following:

If name== ' Ralph ':    print ' welcome! ' Elif name== ' Enid ':    passelif name== ' bill ':    print ' access '

5.7.2 using del Delete

>>> scoundrel={' age ': the ' first name ': ' Robin ', ' Last name ': ' of Locksley '}>>> robin=scoundrel> >> scoundrel{' Last name ': ' of Locksley ', ' First name ': ' Robin ', ' age ': 42}>>> robin{' last name ': ' of LOCKSL EY ', ' First name ': ' Robin ', ' age ': 42}>>> coundrel=none>>> robin{' last name ': ' of Locksley ', ' First name ' ': ' Robin ', ' age ': 42}>>> robin=none

First, both Robin and scoundrel are bound to the same dictionary. So when setting scoundrel to None, the dictionary is still available through Robin. But when I set Robin to none, the dictionary is "floating" in memory, with no name tied to it. There is no way to get and use it, so the Python interpreter (with its infinite Intelligence) deletes the dictionary directly (this behavior is called garbage collection).

>>> x=["Hello", "World"]>>> y=x>>> y[1]= "python" >>> x[' hello ', ' python ']>> > del x>>> y[' hello ', ' python ']>>> xtraceback (most recent call last):  File "<input>", Lin E 1, in <module>nameerror:name ' x ' are not defined

5.7.3 using EXEC and eval to execute and evaluate strings

1. exec
The statement executing a string is exec:

>>> exec "print ' hello,world! '" hello,world!
>>> from math import sqrt>>> exec "sqrt=1" >>> sqrt (4) Traceback (most recent call last):  Fi Le "<input>", line 1, in <module>typeerror: ' int ' object was not callable

The most useful part of the EXEC statement is the ability to dynamically create code strings. If a string is obtained from somewhere else-most likely a user-then it is almost impossible to determine exactly what code it contains. So for security reasons, you can add a dictionary that acts as a namespace.

This can be achieved by adding in<scope>, where <seope> is the dictionary that plays the role of placing the code string namespace.

>>> from math import sqrt>>> scope={}>>> exec "sqrt=1" in Scope>>> sqrt (4) 2.0> >> scope[' sqrt ']1

As you can see, the potentially destructive code does not overwrite the SQRT function, the original function works, and the variable sqrt assigned by exec is only valid within its scope. Note that if you need to print the scope out, you'll see that it contains a lot of things, because the built-in _builtins_ dictionary automatically contains all of the built-in functions and values:

>>> len (Scope) 2>>> Scope.keys () [' __builtins__ ', ' sqrt ']

2.eval

Eval (for "evaluation") is a built-in function similar to exec. The EXEC statement executes a series of Python statements, and eval evaluates the Python expression (written as a string) and returns the result value (the EXEC statement does not return any objects because it is itself a statement). For example, you can use the following code to create a python calculator:

>>> eval (raw_input ("Enter an Arthmetric expression:")] Enter an arthmetric expression:6+18*242

5.8 Summary

New functions in this chapter

Chr (n) returns the string containing one character represented by N when the ordinal n is passed in, (0, n< 256)
Eval (Source[,globals[,locals]]) evaluates the word Fuschen as an expression and returns the value
Enumerate (SEQ) produces the (index, value) pair for the iteration
Ord (c) returns the int value of a single character string
Range ([Start,]stop[,step]) creates a list of integers
Reversed (SEQ) produces a reverse version of the value in the SEQ for iteration
Sorted (Seq[,cmp][,key][,reverse]) returns a list of sorted values in SEQ
Xrange ([Start,]stop[,step]) creates xrange objects for iteration
Zip (seq1,_eq2 ....) Create a new sequence for parallel iterations

"Basic Python Tutorial" Reading notes fifth (next) circular statements

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.