Friday, June 15

Learning Python 5: if and loops

Some control flows.

Before that, more about boolean. In Python, we could use and and or to connect two boolean statement like if a == 3 and b == 4. Turns out they have one more usage. If we simply type in 2 or 3, the interpreter would return 2; also for 2 and 3, it returns 3. How it works:
1. for or test, Python evaluates objects from left to right and return the first one that is True;
2. for and test, Python evaluates objects from left to right and returns the first one that is False.
This becomes handy when we have a situation if a exists then return a, else return b. Using or/and test we could reduce the code.

Moreover, Python does not support switch/case control flow, for that you have to use either multiple if/else, or a dictionary. How to use a dictionary?

a = {1:'ham', 2:'pie', 3:'cheese'}print a.get(2, 'choice is not available')
I think it's nice.

1. for/while

In Python, looks like while is never a popular choice. The book constantly states that while this problem could be solved by while it is often more efficient to use for loop. Noted neither while nor for loop require indexing, so that those who get used to use index inside the loop would be dead already. Most of the time actually programmers do not need to worry about the index details themselves, but if you need to get your hand on the index you could use range(). Also, there is a built-in function called enumerate comes to rescue:

  1. >>> S = 'spam'>>> for (offset, item) in enumerate(S):
    ...   print item, 'appears at offset', offset 
    ... s appears at offset 0 p appears at offset 1 a appears at offset 2 m appears at offset 3 

It turns out else could be combined with while/for loop to ease our coding job in several situations. An else block after the loop actually means, assuming there is a break statement in the loop, if the break does not get executed, i.e. the loop finishes normally, then the else block will be executed. One major scene would be setting flag to check if something happens; now it looks like this:

x = y / 2while x > 1:  if y % x == 0:    print y, 'has factor', x    break  x = x-1 else:  print y, 'is prime'
Previously you have to set a flag and change it if the if statement happens, now it turns into an else outside.


2. iterator

Iterator, an object with a next method to traverse a certain container. Iterator in reading file:
for line in open('your/file', 'r'):
  print line
This is considered to be the best way to read a file in book, because it will not load the file into the memory.

Dictionary comes with iterator like D.keys(); it is also a iterator itself: for keys in D. Other iterators like list comprehension, sorted(), any(), all() method, map and zip function, etc. From the book, I am not so sure about what is an iterator and what is not. Would update this one later.

No comments:

Post a Comment