**********************************************************
一、變數 Variable 與常數 Constant
**********************************************************
變數
---------------------------------
程式執行過程中,可以被改變的資料
x=3
x=x+2
print(x)
5
type(print)
<class 'builtin_function_or_method'>
dir()
['LstA', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'i']
#列出有那些 builtin_function_or_method
dir(__builtins__)
.
.
'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
常數
---------------------------------
程式執行過程中,不能被改變的資料
import math
type(math)
<class 'module'>
math.pi
3.141592653589793
#列出有那些 modules
help("modules")
Please wait a moment while I gather a list of all available modules...
.
.
abc gzip run zoomheight
aifc hashlib runpy zzdummy
antigravity heapq runscript
變數命名規則
---------------------------------
- 變數名稱第一個字元,必須是英文字母、底線或中文(不建議),後即可搭配數字
- 變數名稱區分大小寫
- 不能使用python內建的保留字:關鍵字 keyword、指令
import keyword
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'keyword']
type(keyword)
<class 'module'>
dir(keyword)
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'iskeyword', 'issoftkeyword', 'kwlist', 'softkwlist']
#列出 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']
keyword.iskeyword("else")
True
keyword.iskeyword("name")
False
**********************************************************
二、資料型態 DataType
**********************************************************
文字串Text String Type
---------------------------------
name="Tom"
type(name)
<class 'str'>
數值 Numeric Types
---------------------------------
整數 Integer
total=100
type(total)
<class 'int'>
浮點數 FloatPoint
myPi=3.14
type(myPi)
<class 'float'>
複數 Complex
myComplex=3+2j
type(myComplex)
<class 'complex'>
布林 Boolean Type
---------------------------------
myBoolean=5>3
myBoolean
True
type(myBoolean)
<class 'bool'>
myBoolean=5<3
myBoolean
False
type(myBoolean)
<class 'bool'>
序列 Sequence Types
---------------------------------
串列 List #變數宣告後,可以變更當中資料
ListA=["apple", "banana", "cherry"]
type(ListA)
<class 'list'>
ListB=["Tom",85,70,92]
type(ListB)
<class 'list'>
序對Tuple #變數宣告後,不可變更當中資料
TupleA=("Sun","Mon","Wed")
type(TupleA)
<class 'tuple'>
範圍 Range
---------------------------------
range(1,5+1)
range(1, 6)
type(range(1,5+1))
<class 'range'>
help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
for i in range(1,5+1):
print(i)
1
2
3
4
5
Mapping Type
---------------------------------
字典 Dictionary
DicWeek={0:"Sunday",1:"Monday",2:"Tuesday"}
type(DicWeek)
<class 'dict'>
DicWeek.keys()
dict_keys([0, 1, 2])
DicWeek.values()
dict_values(['Sunday', 'Monday', 'Tuesday'])
集合Set Type
---------------------------------
SetWeek={"Wednesday","Thursday","Friday","Saturday"}
type(SetWeek)
<class 'set'>
Set1={"A","B","C"}
Set2={"B","C","D","E"}
Set1>=Set2 #Set1 是否包含 Set2所有元素
False
Set1<=Set2
False
Set1|Set2 #聯集
{'E', 'C', 'B', 'D', 'A'}
Set1&Set2 #交集
{'C', 'B'}
Set1-Set2 #差集,Set1 有,Set2沒有的元素列出
{'A'}
Set1^Set2 #互斥或xor, Set1和Set2共同元素外的組合
{'E', 'D', 'A'}
**********************************************************
三、運算子 Operator
**********************************************************
help('+')
Operator precedence
*******************
The following table summarizes the operator precedence in Python, from
highest precedence (most binding) to lowest precedence (least
binding). Operators in the same box have the same precedence. Unless
the syntax is explicitly given, operators are binary. Operators in
the same box group left to right (except for exponentiation, which
groups from right to left).
.
.
.
算數運算子 Arithmetic Operator
---------------------------------
x=13;y=2
x+y
15
x-y
11
x*y
26
x/y
6.5
x**y #次方
169
x//y #除法取整數商
6
x%y #除法取餘數
1
指定運算子 Assignment Operator
---------------------------------
weight=70
weight=weight+5
print(weight)
75
關係運算子 Comparison Operators
---------------------------------
a=5;b=2
a>b
True
a>=b
True
a<b
False
a<=b
False
a==b #等於
False
a!=b #不等於
True
邏輯運算子 Logical Operators
---------------------------------
5<7
True
3>8
False
5<7 and 3>8
False
5<7 or 3>8
True
not 5<7
False
not 3>8
True
複合指定運算子 Compound Assignment Operator
---------------------------------
weight=70
weight=weight+5
print(weight)
75
weight=weight+5
weight+=5
weight=weight-5
weight-=5
weight=weight*5
weight*=5
weight=weight/5
weight/=5
Identity Operator
---------------------------------
x='BC';y="ABCD"
x is y
False
x is not y
True
Membership Operator
---------------------------------
x='BC';y="ABCD"
x in y
True
x not in y
False
**********************************************************
四、標準輸入指令:input
**********************************************************
>>> help(input)
Help on built-in function input in module builtins:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
>>> name=input("輸入你的名字:")
輸入你的名字:小明
>>> name
'小明'
>>> type(name)
<class 'str'>
>>> score=int(input("輸入分數:"))
輸入分數:93
>>> score
93
>>> type(score)
<class 'int'>
**********************************************************
五、標準輸出指令:print
**********************************************************
>>> help(__builtins__.print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>> print('A','B','C');print('D','E')
A B C
D E
>>> print(1,2,3,sep='+',end="=")
1+2+3=
format指令,格式化輸出
---------------------------------
na1="John";na2="Ku"
age1=16;age2=7
height1=176.8;height2=98.9
print("名字:{0:4s} 年齡:{1:2d} 身高:{2:6.2f}".format(na1,age1,height1))
print("名字:{0:4s} 年齡:{1:2d} 身高:{2:6.2f}".format(na2,age2,height2))
名字:John 年齡:16 身高:176.80
名字:Ku 年齡: 7 身高: 98.90
#String靠左對齊,Integer靠右對齊,Float對齊小數點
**********************************************************
六、結構化的程式設計 Structured Programming
**********************************************************
其主要精神就是將問題從上而下、由大到小逐步分解成較小單元,這些單元稱為模組 module,又可再細分更小的單元,不但方便程式撰寫,減輕程式設計師負擔,讓程式設計師針對各模組開發設計,日後修改與維護都較為容易。
結構化程式設計包含三種流程控制結構:
循序 Sequential Structure
---------------------------------
x=3
y=6
print(x+y)
9
選擇 Selection Structure
---------------------------------
if 條件運算式:
程式區塊
~~~~~~~~
help('if')
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
height=int(input("輸入身高:"))
if height>=160:
print("身高中等!")
=========
輸入身高:168
身高中等!
if 條件運算式:
程式區塊1
else:
程式區塊2
~~~~~~~~
Num=int(input("輸入一整數:"))
if Num%2==0:
print(Num,"是偶數!")
else:
print(Num,"是奇數!")
=========
輸入一整數:56
56 是偶數!
==========
輸入一整數:33
33 是奇數!
Num=int(input("輸入一整數:"))
print(Num,"是偶數!"if Num%2==0 else "是奇數!")
=========
輸入一整數:12
12 是偶數!
=========
輸入一整數:77
77 是奇數!
a=3;b=6
Min=a if a<b else b
print(Min)
=========
3
for i in range(1,10+1):
print(i if i%2==0 else ' ',end='')
=========
2 4 6 8 10 #奇數只印出空白
if 條件運算式1:
程式區塊1
elif 條件運算式2:
程式區塊2
elif 條件運算式3:
程式區塊3
.
.
else:
程式區塊n
~~~~~~~~
Score=int(input("輸入一整數:"))
if Score>=90:
print("分數A等!")
elif Score>=80:
print("分數B等!")
elif Score>=70:
print("分數C等!")
elif Score>=60:
print("分數D等!")
else:
print("分數E等!")
=========
輸入一整數:100
分數A等!
=========
輸入一整數:85
分數B等!
=========
輸入一整數:73
分數C等!
=========
輸入一整數:68
分數D等!
=========
輸入一整數:59
分數E等!
重複 Repetition Structure
---------------------------------
for item in sequence:
for的程式區塊
else:
else的程式區塊(可省)
~~~~~~~~迴圈次數可以明確
help("for")
The "for" statement
*******************
The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
myRange=range(1,9+1)
for i in myRange:
print(i,end=' ')
=========
1 2 3 4 5 6 7 8 9
for i in range(1,9+1):
print(i,end=' ')
=========
1 2 3 4 5 6 7 8 9
for i in "Hello":
print(i,end=', ')
=========
H,e,l,l,o,
LstA=['Hello','World']
for i in LstA:
print(i)
=========
Hello
World
for i in range(1,6+1):
print(i,end=" ")
else:
print("\n",i," 超出範圍!",sep="")
=========
1 2 3 4 5 6
6 超出範圍! #else之後,i =6 而不是 i=7
while 條件運算式:
符合條件運算式時要執行的程式區塊
else:
不符合條件運算式時要執行的程式區塊
~~~~~~~~迴圈次數不明確定
help("while")
The "while" statement
*********************
The "while" statement is used for repeated execution as long as an
expression is true:
while_stmt ::= "while" assignment_expression ":" suite
["else" ":" suite]
cnt=1
while cnt<=10:
print(cnt,end=' ')
cnt=cnt+1
=========
1 2 3 4 5 6 7 8 9 10
n=1
while n <=6:
print(n,end=" ")
n+=1
else:
print("\n",n,"超出範圍!",sep="")
=========
1 2 3 4 5 6
7超出範圍! #else之後,n =7 而不是 n=6
cnt=1
while cnt<=10:
print(cnt,end=' ')
if cnt==6:break
cnt=cnt+1
========= #break 強制終止迴圈
1 2 3 4 5 6
cnt=1
while cnt<=10:
print(cnt,end=' ')
if cnt==6:continue
cnt=cnt+1
============ #continue 跳過目前迴圈後的程式碼,繼續執行下一輪迴圈
1 2 3 4 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6Traceback (most recent call last):
File "C:/Users/kk/Desktop/python/003.py", line 3, in <module>
print(cnt,end=' ')
KeyboardInterrupt
**********************************************************
python 撰寫風格
**********************************************************
#單行註解
''' 以下式多行註解
「;」
敘述很短時,可用半形分號,把多形敘述併成一行。
python 會在指令後,如:while 或 if ,以縮排表示程式區塊 CodeBlock (python 稱 Suite)。
「:」
半形冒號,提醒使用者下一行程式碼必須縮排,預設值則以一個「Tab」鍵,
即4個空白字元來完成縮排。
'''
x=6;y=9
if x<y:
print("正確")
else:
print("不正確")
=========
正確
**********************************************************
變數交換
**********************************************************
a=3;b=5
tmp=a
a=b
b=tmp
print("a=",a,",","b=",b)
=========
a= 5 , b= 3
a=7;b=9
a,b=b,a
print("a=",a,",","b=",b)
=========
a= 9 , b= 7
**********************************************************
函式 Functtion
**********************************************************
內建函式 Built-In Function 👉 直接使用
---------------------------------
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
dir(__builtins__)
.
.
'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr',
.
type(__builtins__)
<class 'module'>
help(__builtins__)
Help on built-in module builtins:
NAME
builtins - Built-in functions, exceptions, and other objects.
.
.
type(abs)
<class 'builtin_function_or_method'>
x=-3.6
print(abs(x))
3.6
標準函式庫 Standard Library 👉 import 後才可使用
---------------------------------
help("modules")
Please wait a moment while I gather a list of all available modules...
.
_heapq codeop math stringprep
.
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".
import math
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math']
type(math)
<class 'module'>
help(math)
Help on built-in module math:
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
.
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
math.pi
3.141592653589793
def 函式名稱 ( [參數] ):
程式區塊
return 值
自訂函式 def 自行定義
---------------------------------
def myAdd(x,y):
answer=x+y
return answer
x=int(input("x="))
y=int(input("y="))
print("x+y=",myAdd(x,y))
=========
x=3
y=6
x+y= 9
外部函式庫的函式 👉先安裝--> import 後才可使用
---------------------------------
**********************************************************
例外處理
**********************************************************
基本的例外錯誤處理(try-except)
不同的例外錯誤處理(different exceptions)
finally區塊(try-except-finally)
自行拋出例外錯誤(raise exceptions)
x=3;y=6
print(z)
print(x+y)
=========
Traceback (most recent call last):
File "C:/Users/User/Desktop/00.py", line 2, in <module>
print(z)
NameError: name 'z' is not defined
x=3;y=6
try:
print(z)
except:
print("Error!")
print(x+y)
=========有捕捉錯誤,所以print(x+y) 可以順利執行。
Error!
9
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************
**************