Skip to main content

Keyword

Keyword 關鍵字

  • 關鍵字 (keyword) 為具有語法功能的保留字
  • Python 只有 33 個關鍵字,簡略分成這五大類
  • 常數 (False, None, True)
  • 運算子 (and, del, in, is, lambda, not, or)
  • 簡單陳述 (as, assert, break, continue, from, global, import, nonlocal, pass, raise, return, yield)
  • 複合陳述 (else, elif, except, finally, for, if, try, while, with)
  • 定義 (class, def)
>>>print(keyword.iskeyword('123')) //測試是否為關鍵字

Identifier 識別字

  • 識別字是用來區分不同變數(variable),函數(function),類別(class),其規則如下:
  • 可以由字元A-Z,a-z,0-9,_所組成
  • 第一個字元不能是數字
  • 大小寫有差
  • 不能使用Keyword
>>>print("myname".isidentifier()) //測試是否為合格的識別字

Literal 字面量

  • 用來給變數常數使用的原始資料,包含:
  • Numeric Literals:Decimal(30,50), Binary(0b11001), Octal(0o156), Hexadecimal(0x12)
  • String Literals:使用單引號或雙引號去顯示的字串
  • Bytes Literals:
  • Boolean Literals:True or False
  • Special Literals:

Comment 註解

#單行註解
'''多行註解'''
# this is a comment
'''
this is a muti-line comment
'''

多行敘述

  • 可以用反斜線()把多行視為是同一行的指令
if a < 10 and b > 5 \
and c < 6 and d > -1:
print('do something')

縮排

  • Python用縮行來表示一個程式區塊
  • 相同縮排表示這些程式為同一區塊
  • 常使用4個空白健或TAB做縮排
  • 不能混用4個空白健及TAB,會出現錯誤

Print函數

  • Print可以將資訊顯示在螢幕上
print('abc') //顯示abc
print('hello', end='') //end=''就不會換行
print('abc') //hello abc 會顯示在同一行

Input函數

  • Input函數可以讓使用者從鍵盤上輸入字串
my_name = input('please input your name') //接收使用者輸入
print('hello ', my_name)

Format函數

  • Format函數可以將字串格式化
a = 3
b = 2
print('a is {} b is {}'.format(a,b)) //{}是預留空間,結果是 a is 3 b is 2
mytext = 'world'
print('hello {}'.format(mytext)) //帶入變數
name = 'Jack'
text = 'world'
print('hello {name}, hello {text}'.format(name=name, text=text)) //也可以使用名稱來指定變數變換順序
print('this is firstline \n this is second line') //會出現兩行

Type函數

  • Type函數可以顯示出變數的資料型態
number = input('input a number') //請使用者輸入數字
print(type(number)) //會是字串str
number = int(number) //會轉換為整數
number = float(number) //會轉換為浮點數