Python Learning Path-control statements, iterators, list parsing

Source: Internet
Author: User
Tags iterable

Conditional statements ifare all old friends, direct code example, simple and easy to get started:
<span style= "FONT-SIZE:18PX;" >>>> lang = "python" >>> if lang = = "C":     ... Print "C language" ... elif lang = = "Java": ...     Print "Java language" ... else:     Print "Python language" ... Python language>>> </span><span style= "FONT-SIZE:14PX;" ></span>

Looping Statements whiledirectly on the code, is the dry
<span style= "FONT-SIZE:18PX;" >>>> count = 0>>> while (Count < 9): ...     print ' The index is: ', Count ...     Count + = 1 ... The index is:0the Index is:1the Index is:2the Index is:3the Index is:4the Index is:5the index is:6the index is:7th E index is:8>>> </span><span style= "FONT-SIZE:14PX;" ></span>

fornot explained, directly on
<span style= "FONT-SIZE:18PX;" >>>> game = [' LOL ', ' GT ', ' CSOL ']>>> for G in game: ...     print ' You play%s '% game ... you play [' LOL ', ' GT ', ' CSOL ']you play [' lol ', ' GT ', ' CSOL ']you play [' lol ', ' GT ', ' CSOL ']&G T;>> for index in range (len (game)): ...     print ' You play%s '% Game[index] ... you play lolyou play Gtyou play csol>>> </span><span style= "Font-si ze:14px; " ></span>

Break , continue, passbreak: Familiar with C's friends are familiar, breaking the cyclecontinue: Skip the following statement and proceed directly to the next loopPass: An empty statement, such as a C-hollow curly brace
While-else, For-else (still quite handy)When the loop and Else statement are used together (the description is not very accurate, the code is understood), the loop exits normally, and the statement in else is run. How the loop ends with a break statement, then the statement in else will also be skipped. The following code is quoted in the book:maxfact.py
<span style= "FONT-SIZE:18PX;" >def showmaxfactor (num):        count = num/2 while        count > 1:                if num% count = = 0:                        print ' largest factor o F%d is%d ' percent (NUM, count) break                        ;                Count-= 1        else:                print num, ' is prime ' for Eachnum in range (10,21):        showmaxfactor (eachnum) </span> <span style= "FONT-SIZE:14PX;" ></span>
Operation Result:
<span style= "FONT-SIZE:18PX;" >linux-ne7w:~/python> python maxfact.py largest factor of 511 is primelargest factor of are 613 EST factor of 7largest factor of is 5largest factor of are 817 is primelargest factor of are 919 is Primelarg EST factor of 10</span><span style= "FONT-SIZE:14PX;" ></span>

iteratorsiterators provide an interface for class sequence objects with a sequence of classes. Iterators are very flexible and can iterate over objects that exhibit the sequence behavior. For example, a dictionary key, all lines of a file, and so on.
    • Why iterators:
    • Provides an extensible iterator interface
    • Provides performance enhancements to list iterations
    • Performance improvements in dictionary iterations
    • Create a real iterative interface instead of the original random object access
    • Backwards compatibility with all existing user-defined classes and extended simulated sequences and mapped objects
    • You can create more concise and readable code when iterating over a non-sequential collection
How to Iterate:You can first use the ITER () function to return an iterator to the iterated object, and then call the next () method of the iterator to get the next item. When all items are fetched, a Stopiteration exception is thrown, telling the caller that the iteration is complete. Iterators are unidirectional and can only be moved backwards. using iterators:
<span style= "FONT-SIZE:18PX;" >>>> T = (123, ' text ', 66.66) >>> T (123, ' text ', 66.66) >>> i = iter (t) >>> I.next () 12 3>>> i.next () ' Text ' >>> i.next () 66.66>>> i.next () Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>> </span><span style= "FONT-SIZE:14PX;" ></span>
in practical applications, this is a real story. Python is really smart, and in real-world applications, Python will handle it for you. See an example of an iterative file
<span style= "FONT-SIZE:18PX;" >>>> f = open (' Text.txt ', ' R ') >>> for eachline in F: ...      Print Eachline,... This was just for a testeveryone should learn programming, programming teach you thinking.forget my poor english.haha.</ Span><span style= "FONT-SIZE:14PX;" ></span>
The For loop automatically invokes the next () method of the iterator and handles the stopiteration exception.
Warning: Do not modify it when iterating over mutable objects, then boom, the program crashes.
List Parsinglist comprehensions is derived from the functional programming language Haskell. It is used to dynamically create lists. Syntax for list parsing:[expr for Iter_var in iterable]by my understanding (generating list elements), it is equivalent to:For Iter_var in iterable: Expr
See a few examples:
<span style= "FONT-SIZE:18PX;" >[X * * 2 for X in range (6)][0, 1, 4, 9,, 25]>>> seq = [One, ten,,, A,,, Max, 32]>>> [x for x in seq if x% 2] [One, the 21]</span>, the
<span style= "FONT-SIZE:18PX;" >>>> [(x+1,y+1) for the X in range (3) for Y in range (4) [(1, 1), (1, 2), (1, 3), (1, 4), () and 2), (1, 2), (2, 2), ( 2, 4), (3, 1), (3, 2), (3, 3), (3, 4)]>>> </span><span style= "FONT-SIZE:14PX;" ></span>

Builder ExpressionA builder expression is an extension of list resolution. Not very familiar at the moment, let's do it first.





Python Learning Path-control statements, iterators, list parsing

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.