head first python(第一章)--學習流程圖

1.安裝python
這里是用python3的,除了windows之外,linux和macos都自帶了,只是版本沒有這么新。
舉例:centos 6.5的python版本為2.6:
python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
python3和2主要是有些語法和功能有些微區別,但不影響本書閱讀。
python有一個自帶的idle環境,如上面代碼,可以用來測試代碼和查看幫助文檔
例如:
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
查看list的幫助
>>> help(list)
>Help on class list in module __builtin__:
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
| Methods defined here:
| __add__(...)
| x.__add__(y) <==> x+y
有一些術語需要了解,內置函數BIF 就是build in function,就是python一般自帶的函數,可以直接調用,例如直接print 輸出
2.處理復雜數據
1.列表
movies = ["The holy grail","the life of brain","0.02,"["the second list","abc"]"]
python的變量標識符沒有類型,例如,列表只是一個高層的集合,他不關心列表存的是什么數據.
列表就像數組,有下標,例如print(movies[1]),有長度len(movies)
可以列表末尾增加數據movies.append(),列表末尾刪除數據moveis.pop(),列表增加列表movies.extend(["abc","cde"]),指定刪除特定數據movies.remove(括號內是值,value),指定在特定位置增加數據movies.insert(1,"aaa")
對于已有列表的情況下,考慮如何增加列表數據比較好?
答案是使用insert()函數,延伸思考刪除和管理列表數據方法。
2.for循環,迭代數據
如果想處理每一個列表的數據項,就需要迭代數據了
for each in movies:
print(each)
經典for循環,for 目標標識符 in 列表:
疑問:
1.Q:有些字符串用雙引號引起來,而有些用單引號
A: PYTHON中沒有規定要使用哪一種,只有一個規則,如果字符串前面使用了某個單引號或者雙引號,那么字符串后面也要使用同樣的,一般情況下,引號是為了創建字符串的。
2.Q:如果需要在一個字符串中嵌入一個雙引號改怎么做?
A: 用\進行轉義,或者使用單引號引起這個,不過通常來說用\比較好看。
3.python是區分大小寫的。
3.在列表中存儲列表
python中列表是可以存儲任何東西的,哪怕是列表,所以列表嵌套列表是可以的,如果要訪問a列表中第二項(也是列表)的第三項數據,就是print(movies[2][3]),如此類推。可以根據多維數組來理解。
如果遇到列表嵌套列表的情況,那么單純的for循環并不能很好的訪問數據項,所以需要利用if 和isinstance來判斷
for each_item in movies:
if isinstance(each_item,list):
for nested_item in each_item:
print(nested_item)
else:
print(each_item)
判斷是否是列表,是的話增加一個迭代,不是的話就直接打印當前值,嵌套越深就要增加越多判斷代碼
4.不重復代碼,使用函數
因為上面遇到代碼越來越多的問題,而且代碼重復的情況嚴重,所以需要使用函數def
def 函數名(參數):
函數代碼組
將上面的代碼 函數化之后
def print_lol(the_list):
for each_item in the_list:
if isinstance(each_tem,list):
print_lol(each_item)
else:
print(each_item)
如果處理的是列表則使用print_lol(),如果不是的話就使用普通的print
使用的時候就可以使用
print_lol(movies)
很靈活,而且代碼也規范了,如果需要修改的話就直接修改def內的函數體。
知識點補充:
1.python里列表是"打了激素"的數組,意味著列表比數組更厲害,更好用。
2.python的語句的縮進是必須規范的。
原文鏈接:http://www.godblessyuan.com/2015/04/13/head_first_python_chapter_1_learning/