Python基礎:語法基礎(3)

libingql發表於2018-12-22

本篇主要介紹Python中一些基礎語法,其中包括:識別符號、關鍵字、常量、變數、表示式、語句、註釋、模組和包等內容。

1. 識別符號和關鍵字

1.1 識別符號

  識別符號是變數、常量、函式、屬性、類、模組和包等指定的名稱,Python語言中識別符號的命名規則如下:

  (1)區分大小寫,例Name與name是兩個不同的識別符號;

  (2)識別符號首字母可以是下劃線“_”或字母,但不能是數字;

  (3)識別符號除首字母外的其它字元,可以是下劃線“_”、字母和數字;

  (4)關鍵字不作為識別符號;

  (5)Python內建函式不能作為識別符號。

1.2 關鍵字

  Python語言中有33個關鍵字,其中只有三個(即True、False和None)首字母大寫,其它均為全部小寫。

>>> help()

Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               class               from                or
None                continue            global              pass
True                def                 if                  raise
and                 del                 import              return
as                  elif                in                  try
assert              else                is                  while
async               except              lambda              with
await               finally             nonlocal            yield
break               for                 not

2. 變數和常量

2.1 變數

  在Python中宣告變數時,不需要指定資料型別。Python是動態型別語言,不會檢查資料型別,在宣告變數時不需要指定資料型別。

  在使用變數前需要對其賦值。沒有賦值的變數是沒有意義的,編譯器會編譯不通過。

  同一個變數可以反覆賦值,而且可以是不同型別的變數。

  當不能確定變數或資料的型別時,可以使用直譯器內建的函式type進行確認。

>>> hello = 'Hello World!'
>>> hello
'Hello World!'
>>> type(hello)
<class 'str'>
>>> hello = 100
>>> hello
100
>>> type(hello)
<class 'int'>

2.2 常量

  Python不能從語法上定義常量,Python沒有提供一個關鍵字使得變數不能被修改。

  Python中只能講變數當成常量使用,只是不要修改它。