Python學習筆記1:基礎
阿新 • • 發佈:2020-11-12
1.編碼
預設情況下,Python 3 原始碼檔案以 UTF-8 編碼,所有字串都是 unicode 字串。
你也可以為原始檔指定不同的字元編碼。在 #! 行(首行)後插入至少一行特殊的註釋行來定義原始檔的編碼:
# -*- coding: utf-8 -*-
或
# -*- coding: cp-1252 -*-
2.識別符號
第一個字元必須是字母表中字母或下劃線 _ 。
識別符號的其他的部分由字母、數字和下劃線組成。
識別符號對大小寫敏感。
3.python保留字
保留字即關鍵字,我們不能把它們用作任何識別符號名稱。Python 的標準庫提供了一個 keyword 模組,可以輸出當前版本的所有關鍵字:
>>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] >>>
4.註釋
Python中單行註釋以 # 開頭,例項如下:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# First comment
print("Hello world!")
Python中使用三個雙引號或單引號來註釋多行內容,例項如下:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
First comment
Line 1
Line 2
'''
"""
Second comment
Line 1
Line 2
"""
print("Hello world!")
5.縮排
python最具特色的就是使用縮排來表示程式碼塊,不需要使用大括號 {} 。
縮排的空格數是可變的,但是同一個程式碼塊的語句必須包含相同的縮排空格數。例項如下:
if True:
print("This is true")
else:
print("This is false")
如果語句縮排數的空格數不一致,會導致執行錯誤:
if True:
print("This is true")
else:
print("This is false")
print("This is error") # error
IndentationError: unindent does not match any outer indentation level