Friday, June 15

Learning Python 4: other types, expressions

There are some other types, sets, files, etc.

For files, you could open/read/write/close as usual. Just a note that, you have to convert everything you try to put into a file into string before you put them in, including your objects. And also when you read them from the file, they are strings. There is a way to maintain their characters: use pickle module. Say you have a list a = [1,2,3] and you want to store it in a file:
import pickle
aFile = open("path/to/your/file","a")
pickle.dump(a, aFile)
b = aFile.load(a)
Then b is still a list. What does it do is taking care of this conversion so you don't have to worry about; it's called object serialization.

Then there is boolean. Actually in Python, every object (so does every variable) has a boolean property: they are interpreted as either True or False. Two general rules: (1). numbers are true if nonzero; (2). other objects are true if nonempty. As a result, in a block started with if "", nothing would be executed in it. However, "" == False will return False because "" is not False; it is just interpreted as False. It turns out that bool, the boolean type of Python is a subclass of int, therefore if you use 1 == True, the interpreter will return True.

 Overall, here is a type hierarchy I captured from the book:

Then about syntax and expression in Python, one thing is the indentation stays in every block, which means if one block of yours use tab as indentation and another use space it is still fine. To be honest, after I know this rule exists, I follow it whenever and wherever I could. It just builds more readable code.

For expressions, there are some new tricks: A < B < C, equivalent to A < B and B < C; a += 1, which is faster that a = a + 1 for a will only be evaluated once in the former.


No comments:

Post a Comment