Python BASICS (9): Conditions and loops, 2015 python

Source: Internet
Author: User
Tags case statement iterable

Python BASICS (9): Conditions and loops, 2015 python

Condition Statement
The if statement in Python is as follows:

if expression:  expr_true_suite

Here, expression can use the boolean operators and, or, and not to implement multiple judgment conditions.
If the code block of a compound statement only contains one line of code, it can be written in the same line as the preceding statement:

if expression: dosomething

But in fact, we try not to do this for readability.
Use of else statements:

if expression:  expr_true_suiteelse:  expr_false_suite

Python uses indentation to force code alignment, which can avoid the issue of creating some types of else suspension. But we also need to be very careful about code alignment, otherwise the Code may not be used.
Elif (else-if) Statement
Python does not have a switch/case statement, so if-elif is used in place of it does not reduce reading performance.

if user.cmd == 'create':  action = "create item"elif user.cmd == 'delete':  action = 'delete item'elif user.cmd == 'update':  action = 'update item'else:  action = 'invalid choice... try again!'

The preceding statement can also be rewritten in sequence:

if user.cmd in ('create', 'delete', 'update'):    action = '%s item' % user.cmdelse:    action = 'invalid choice... try again!'

Or a dictionary Solution

msgs = {'create': 'create item','delete': 'delete item','update': 'update item'}default = 'invalid choice... try again!'action = msgs.get(user.cmd, default)

 


Conditional expressions ("ternary operators ")
That is, C in C? X: Y
Python uses X if C else Y:

>>> x, y = 4, 3>>> smaller = x if x < y else y>>> smaller3

 

While statement
The general syntax of the while loop is as follows:

while expression:  suite_to_repeat

A while LOOP is generally used as a Count loop or an infinite loop:

>>> count = 0>>> while (count < 9):    print 'the index is:', count    count += 1the index is: 0the index is: 1the index is: 2the index is: 3the index is: 4the index is: 5the index is: 6the index is: 7the index is: 8>>>while True:    message = raw_input("please input :")    if message.lower() == 'q':    break

 

For statement
Python for is very powerful. It can traverse sequence members and can be used in list parsing and generator expressions. It automatically calls the next () method of the iterator, capture StopIteration exceptions and end the loop (this occurs internally). The for loop in Python is different from the for Loop in traditional languages, similar to the foreach loop in shell.

General syntax
For Loop accesses all elements in an iteratable object (such as a sequence or iterator), and ends the loop after all entries are processed

for iter_var in iterable:  suit_to_repeat

For loop iteration of different sequence objects, the following example:

>>> For eachLetter in 'names': # iteration string print 'current letter: ', eachLettercurrent letter: Ncurrent letter: acurrent letter: mcurrent letter: ecurrent letter: s >>> nameList = ['amy ', 'bob', 'henry'] >>> for eachName in nameList: # print eachName, 'lim' Amy LimBob LimHenry Lim >>> for nameIndex in range (len (nameList): # iterative index print "Liu,", nameList [nameIndex] Liu, amyLiu, BobLiu, Henry >>> nameList = ['donn', 'Shirley ', 'ben', 'Jane'] >>>> for I, eachone in enumerate (nameList ): # use item and index iteration print '% d % s' % (I + 1, eachone) 1 Donn2 Shirley3 Ben4 Jane

 

The for loop access iterator is similar to the access sequence method, but the for statement does some extra work, and the iterator does not represent the set of loop entries.
The iterator object has a next () method, and the next entry is returned after the method is called. A StopIteration exception is thrown after iteration to tell the program that the loop ends. For calls next () internally and captures exceptions.

The range () built-in functions are described in detail in the previous blog article Python basic usage (2. I will not repeat it here

Xrange ()
Xrange () is similar to range (). When a list range is large, xrange () is more suitable because it does not create a full copy of the list in the memory and can only be used in a for loop, it makes no sense outside of the for loop. The performance is much higher than range ().

Sorted (), reversed (), enumerate (), zip ()

>>> for album in sorted(albums):    print album,Freud Gaudi Poe Poe2>>> for album in reversed(albums):    print album,Poe2 Freud Gaudi Poe>>> for i, album in enumerate(albums):    print i, album0 Poe1 Gaudi2 Freud3 Poe2>>> for album, yr in zip(albums, years):    print yr, album1976 Poe1987 Gaudi1990 Freud2003 Poe2

 

Break and continue statements

The break, continue and the break in C are very similar.
Pass statement
Because Python does not have traditional brackets, pass indicates that this code block does not do anything.

In addition, loop statements can also be connected to else statements.
This code block is executed after the loop ends.

 

Iterator and iter () Functions
The iterator provides an interface for class sequence objects. The index can be used to iterate from 0 to the last entry of the sequence. It is very easy to use the counting method to iterate the sequence. Python iterations seamlessly support sequence objects and allow non-sequence types, including user-defined objects.
The iterator is very clever to use. It can iterate objects that are not sequences but show sequence behavior, such as Dictionary keys and lines of a file. Python does not focus on the iterator or sequence when it is used for iteration, because Python allows it to operate like a sequence.
Use iterator:
Sequence:

>>> myTuple = (123, 'xyz', 45.67)>>> i = iter(myTuple)>>> i.next()123>>> i.next()'xyz'>>> i.next()45.67>>> i.next()Traceback (most recent call last):File "<pyshell#5>", line 1, in <module>i.next()StopIteration

 

If this is an actual application, we need to put the code in a try-nothing t block. The sequences now automatically generate their own iterators, so a for Loop:

for i in seq:  do_something_to(i)

 

It actually works like this:

fetch = iter(seq)while True:  try:  i = fetch.next()  except StopIteration:  break  do_something_to(i)

 

Dictionary: The dictionary iterator traverses its key (keys)

>>> legends = {('Poe', 'author'):(1809, 1849, 1976),}>>> legends = {('Poe', 'author'):(1809, 1849, 1976),('Gaudi','architect'):(1852, 1906, 1987),('Freud', 'psychoanalyst'):(1856, 1939, 1990)}>>> for eachLegend in legends:    print 'Name: %s\tOccupation: %s' % eachLegend    print 'Birth: %s\tDeath: %s\tAlbum:%s\n' % legends[eachLegend]Name: Poe    Occupation: authorBirth: 1809    Death: 1849    Album:1976Name: Gaudi    Occupation: architectBirth: 1852    Death: 1906    Album:1987Name: Freud    Occupation: psychoanalystBirth: 1856    Death: 1939    Album:1990

 

In addition, Python introduces three new built-in dictionary methods to define iteration: myDict. iterkeys () (iterated by keys), myDict. itervalues () (iterated through values) and myDict. iteritems () (iterations through key/value pairs)

File
The iterator generated by the file object automatically calls the readline () method, so that the loop can access all rows of the text file. Programmers can replace for eachLine in myFile with for eachLine in myFile. readlines ():

>>> myFile = open('config-win.txt')>>> for eachLine in myFile:...   print eachLine, # comma suppresses extra \n...[EditorWindow]font-name: courier newfont-size: 10>>> myFile.close()

 

Variable object and iterator
It is not a good idea to modify variable objects during iteration. The sequence types except the list are immutable, so the danger occurs here. The iterator of the sequence only records the number of elements you have currently reached. If you change the elements during iteration, the update will immediately reflect the entries you have iterated. When the key of the dictionary is iterated, the dictionary cannot be changed (because the dictionary is unordered ). You can use the dictionary's keys () method. Because keys () returns a list independent of the dictionary, and the iterator is bound with the actual object, it will not continue to execute:

>>> myDict = {'a': 1, 'b': 2, 'c': 3, 'd':4}>>> for eachKey in myDict:    print eachKey, myDict[eachKey]    del myDict[eachKey]a 1Traceback (most recent call last):File "<pyshell#4>", line 1, in <module>for eachKey in myDict:RuntimeError: dictionary changed size during iteration

 

Create iterator
Call iter () on an object to obtain its iterator:

iter(obj)iter(func, sentinel)

If you pass a parameter to iter (), it will check whether you pass a sequence. If yes, It is very simple: Always iterate from 0 to the end of the sequence based on the index.
If two parameters are passed to iter (), it repeatedly calls func until the next value of the iterator is sentinel.
Another method for creating an iterator is class. I will learn more in later sections.

List Parsing
List Parsing is a very useful, simple, and flexible tool that can be used to dynamically create a list.
List parsing Syntax:

[expr for iter_var in iterable]

The core is the for loop, which iterates all entries of the iterable object. The expr of the front edge is applied to each member of the sequence. The final result value is the list generated by this expression. Iteration variables do not need to be part of expressions.
Lambda function expression:

>>> Map (lambda x: x ** 2, range (6) # This is the lambda function expression [0, 1, 4, 9, 16, 25] >>> [x ** 2 for x in range (6)] # This is list resolution [0, 1, 4, 9, 16, 25]

List parsing and extended versions combined with if

[expr for iter_var in iterable if cond_expr]

This syntax filters/captures sequential members that meet the condition expression cond_expr during iteration.
The following example is to pick out the odd number in the sequence:

>>> Seq = [11, 12, 16, 13, 10, 9, 9, 10, 8] >>> filter (lambda x: x % 2, seq) # Use filter and lambda to implement [11, 13, 9, 9] >>> [x for x in seq if x % 2] # Use List parsing to implement [11, 13, 9, 9]

 

Generator expression
The generator expression is an extension of list parsing. The syntax is as follows:

(expr for iter_var in iterable if cond_expr)

The syntax is basically the same as list parsing, but it does not actually create a number list. Instead, it returns a generator. After calculating an entry, the generator "generates" the entry (yield. The generator expression uses "latency calculation", so it is more effective in memory usage. This will be described in detail in future studies.

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.