高雄市高中職學生 - "飆程式網"
http://khcode.m-school.tw/
Code Judger
https://www.codejudger.com/
建置開發環境
到官網 https://www.python.org/ 下載 python ,並進行安裝(Cpython)。
及如何執行寫好的 python 程式。
Anaconda 附帶 Jupyter Notebook 從程式碼編寫到執行都可完成。
IDLE
Integrated Development and Learning Environment
>>> import this
The Zen of Python, by Tim Peters
python 程式執行方法:
1.互動模式 interactive mode
kk@ubun:~$ python3
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 表示完成啟動
>>> x=3+6
>>> x
9
不使用print(),也能顯示輸入訊息
ctrl+z 離開互動模式
2.腳本模式 script mode
kk@ubun:~$ mkdir MyPython
kk@ubun:~$ cd MyPython
kk@ubun:~/MyPython$ vi 01.py
x=3+6
print(x)
kk@ubun:~/MyPython$ python3 01.py
9
資料型別 DataType
- 數值 Number
>>> type(3)
<class 'int'>
>>> x=6
>>> type(x)
<class 'int'>
type(3.14)
<class 'float'>
數學中的複數,用「i」來表示虛數的部份,而在Python當中則是用「j」或是「J」來表示
複數Complex = 實部 real + 虛部 imaginary
c=3+5j
type(c)
<class 'complex'>
c.real #實數
3.0
c.imag #虛數
5.0
- 字串String
type("Hello")
<class 'str'>
- Sequence Types:
Lst=[3,5,7]
type(Lst)
<class 'list'>
# 串列 list 元素可為任意不同型別,C/C++ 陣列 Array 元素型別需相同
串列 List 使用--------------------------------------------------------
Lst=["A","B"]
Lst*2
['A', 'B', 'A', 'B']
Lst=['A','B','C','D','E','F','G']
#串列元素數目
len(Lst)
7
#切片Slicing :由 list 中切出一個 list 片段
#取出第1個索引值到第5個索引值
Lst[1:5]
['B', 'C', 'D', 'E']
#取出第1個索引值到第5個索引值,間隔2
Lst[1:5:2]
['B', 'D']
#字串轉入List
Lst=list("ABCDEF")
Lst
['A', 'B', 'C', 'D', 'E', 'F']
Lst=[]
for i in "ABCDEF":
Lst.append(i)
Lst
['A', 'B', 'C', 'D', 'E', 'F']
Lst=[]
Lst[0:]="ABCDEF"
Lst
['A', 'B', 'C', 'D', 'E', 'F']
Lst=list("A B C D E F")
Lst
['A', ' ', 'B', ' ', 'C', ' ', 'D', ' ', 'E', ' ', 'F'] #多空白鍵
Lst=[i for i in "A B C D E F".split()]
Lst
['A', 'B', 'C', 'D', 'E', 'F']
#List轉成字串
Lst=['A','B','C','D','E','F']
Str=','.join(i for i in Lst)
Str
'A,B,C,D,E,F'
Str=''.join(i for i in Lst)
Str
'ABCDEF'
Lst=[1,2,3,4,5]
Str='-'.join(str(i) for i in Lst)
Str
'1-2-3-4-5'
#排序與反轉
Lst=[2,1,5,3,4]
sorted(Lst)
[1, 2, 3, 4, 5]
Lst
[2, 1, 5, 3, 4]
Lst.sort()
Lst
[1, 2, 3, 4, 5]
Lst.reverse()
Lst
[5, 4, 3, 2, 1]
Lst[::-1]
[1, 2, 3, 4, 5]
字串操作
Str="ABCDE"
Str[0]
'A'
Str[4]
'E'
Str[0:1]
'A'
Str[4:5]
'E'
for i in Str:
print(i,end=" ")
A B C D E
len(Str)
5
for i in range(len(Str)):
print(Str[i],end=" ")
A B C D E
for i in range(len(Str)):
print(Str[i:i+1],end=" ")
A B C D E
#字串反轉
for i in range(len(Str),-1,-1):
print(Str[i:i+1],end=" ")
E D C B A
for i in range(len(Str)-1,-1,-1):
print(Str[i],end=" ")
E D C B A
Str
'ABCDE'
#index:0,1,2,3,4
Str[0]
'A'
Str[4]
'E'
#反轉 index:-1,-2,-3,-4,-5
Str[-1]
'E'
Str[-5]
'A'
range(start, stop[, step])
start: 計數從start 開始。預設是從0 開始。例如range(5)等價於range(0, 5);
stop: 計數到stop 結束,但不包括stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]沒有5
step:步長,預設為1。例如:range(0, 5) 等價於range(0, 5, 1)
for i in range(0,5,1):
print(i,end=" ")
0 1 2 3 4
for i in range(4,-1,-1):
print(i,end=" ")
4 3 2 1 0
--------------------------------------------------------
#元組 tuple 可視為其中元素不可更改的 list
Tpl=(3,5,7)
type(Tpl)
<class 'tuple'>
Rng=range(0,5+1)
type(Rng)
<class 'range'>
- Mapping Type:
Dic={0:"Sun",1:"Mon"}
type(Dic)
<class 'dict'>
- Set Types:
mySet={"Sun","Mon"}
type(mySet)
<class 'set'>
- 布林值 Boolean
type(True)
<class 'bool'>
type(False)
<class 'bool'>
- Binary Types:
x=b"Hello"
type(x)
<class 'bytes'>
- None Type:
x=None
type(x)
<class 'NoneType'>
變數 Variable 與常數 Constant
變數
---------------------------------
程式執行過程中,可以被改變的資料
x=3
x=x+2
print(x)
5
常數
---------------------------------
程式執行過程中,不能被改變的資料
import math
type(math)
<class 'module'>
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math']
dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', '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
變數命名規則
---------------------------------
變數名稱第一個字元,必須是英文字母、底線或中文(不建議),後即可搭配數字
變數名稱區分大小寫
不能使用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
+++++++++++++++++++++++++++++++++++++++++++++++++++++
內建函式 builtin_function_or_method
### dir()的用途是用於用來查詢物件的全部屬性。
如果 dir() 的括弧內不帶任何參數物件,執行結果則會最大限度地顯示出當前範圍內的變數、方法和屬性列表。
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
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'
type(str)
<class 'type'>
dir(str)
...
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join',
'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix',
'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
type(str.upper)
<class 'method_descriptor'>
str.upper("abc")
'ABC'
#Unicode 轉字元
chr(65)
'A'
#字元轉 Unicode
ord("A")
65
### help(): 用於查看函式或模組用途的詳細說明。
help("str")
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
...略
| upper(self, /)
| Return a copy of the string converted to uppercase.
type(print)
<class 'builtin_function_or_method'>
dir(print)
['__call__',
'__class__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__',
'__module__', '__name__', '__ne__', '__new__', '__qualname__',
'__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
help("print")
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
模組 modules
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
import math
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math']
dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', '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
help("modules")
Please wait a moment while I gather a list of all available modules...
... math numpy os pip ...略
軟體包 packages
PIP is a package manager for Python packages, or modules if you like.
pip 是 Python 包管理工具,該工具提供了對Python 包的查找、下載、安装、卸載的功能。
可以透過以下命令来判斷是否已安装:
C:\Users\User>pip list
Package Version
------------------ ----------
certifi 2023.5.7
charset-normalizer 3.1.0
colorama 0.4.6
decorator 4.4.2
ffmpeg 1.4
idna 3.4
imageio 2.30.0
imageio-ffmpeg 0.4.8
moviepy 1.0.3
numpy 1.24.3
Pillow 9.5.0
pip 23.3.1
proglog 0.1.10
pygame 2.4.0
pytube 15.0.0
requests 2.31.0
setuptools 65.5.0
tk 0.1.0
tqdm 4.65.0
urllib3 2.0.2
youtube-dl 2021.12.17
C:\Users\User>pip install django
Collecting django
Downloading Django-4.2.7-py3-none-any.whl.metadata (4.1 kB)
Collecting asgiref<4,>=3.6.0 (from django)
Downloading asgiref-3.7.2-py3-none-any.whl.metadata (9.2 kB)
Collecting sqlparse>=0.3.1 (from django)
Downloading sqlparse-0.4.4-py3-none-any.whl (41 kB)
---------------------------------------- 41.2/41.2 kB 499.1 kB/s eta 0:00:00
Collecting tzdata (from django)
Downloading tzdata-2023.3-py2.py3-none-any.whl (341 kB)
---------------------------------------- 341.8/341.8 kB 732.0 kB/s eta 0:00:00
Downloading Django-4.2.7-py3-none-any.whl (8.0 MB)
---------------------------------------- 8.0/8.0 MB 2.3 MB/s eta 0:00:00
Downloading asgiref-3.7.2-py3-none-any.whl (24 kB)
Installing collected packages: tzdata, sqlparse, asgiref, django
Successfully installed asgiref-3.7.2 django-4.2.7 sqlparse-0.4.4 tzdata-2023.3
C:\Users\User>pip list
Package Version
------------------ ----------
asgiref 3.7.2
certifi 2023.5.7
charset-normalizer 3.1.0
colorama 0.4.6
decorator 4.4.2
Django 4.2.7
ffmpeg 1.4
idna 3.4
imageio 2.30.0
imageio-ffmpeg 0.4.8
moviepy 1.0.3
numpy 1.24.3
Pillow 9.5.0
pip 23.3.1
proglog 0.1.10
pygame 2.4.0
pytube 15.0.0
requests 2.31.0
setuptools 65.5.0
sqlparse 0.4.4
tk 0.1.0
tqdm 4.65.0
tzdata 2023.3
urllib3 2.0.2
youtube-dl 2021.12.17
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
import django
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'django']
dir(django)
['VERSION',
'__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__path__', '__spec__', '__version__',
'get_version', 'setup', 'utils']
<class 'module'>
+++++++++++++++++++++++++++++++++++++++++++++++++++++
運算子 OPerators
Arithmetic Operators:
#加
15+7
22
#減
15-7
8
#乘
15*7
105
#除
15/7
2.142857142857143
#兩數相除取餘數
15%7
1
#取得整除的商
15//7
2
#次方
15**7
170859375
Assignment Operators:
x=5
x+=3
x
8
x=5
x-=3
x
2
x=5
x*=3
x
15
x=5
x/=3
x
1.6666666666666667
x=5
x%=3
x
2
x=5
x//=3
x
1
x=5
x**=3
x
125
Comparison Operators
#等於
5==3
False
#不等於
5!=3
True
5>3
True
5<3
False
5>=3
True
5<=3
False
Logical Operators
x=5
x>3 and x<10
True
x>3 or x<10
True
not(x>3 or x<10)
False
Identity Operators
x=3;y=5
x is y
False
x is not y
True
Membership Operators
Lst=["A","B"]
"A" in Lst
True
"A" not in Lst
False
Bitwise Operators
bin(3)
'0b11'
bin(2)
'0b10'
3&2 //二進制 10
2
3|2 //二進制 11
3
3^2 //二進制 01
1
~3 // 3的二進制 0011,反向1100,第一碼1所以是負數,後三碼100即十進制4
-4
12>>3 //右移 除 2**3
3
12<<3 //左移 乘 2**3
96
優先順序:
()
**
+x -x ~x
* / // %
+ -
<< >>
&
^
|
== != > >= < <= is is not in not in
not
and
or
程式流程控制
If ... Else
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]
if 3<6:
True
---------------
True
Short Hand If
if 3<6:True
---------------
True
if 3<6:
True
else:
False
---------------
True
Short Hand If ... Else
True if 3<6 else False
--------------
True
while Loop
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]
x=0
while x<=5:
print(x)
x+=1
---------------
0
1
2
3
4
5
x=0
while x<=5:
print(x)
if x==3:break
x+=1
---------------
0
1
2
3
x=0
while x<=5:
print(x)
x+=1
else:
print("x>=5條件式不成立!")
---------------
0
1
2
3
4
5
x>=5條件式不成立!
For Loops
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" starred_list ":" suite
["else" ":" suite]
Lst=["A","B"]
for i in Lst:
print(i)
---------------
A
B
for i in "AB":
print(i)
---------------
A
B
for i in "ABC":
print(i)
if i=="B":break
---------------
A
B
for n in range(0,6):
print(n)
---------------
0
1
2
3
4
5
for n in range(6):
print(n)
---------------
0
1
2
3
4
5
for n in range(0,6,1):
print(n)
---------------
0
1
2
3
4
5
for n in range(0,6,2):
print(n)
---------------
0
2
4
for n in range(0,6,3):
print(n)
---------------
0
3
輸入input()
>>> help(input)
Help on built-in function input in module builtins:
input(prompt='', /)
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("Please input your name:")
Please input your name:小明
>>> name
'小明'
>>> type(name)
<class 'str'>
>>> score=int(input("Please your score:"))
Please your score:90
>>> score
90
>>> type(score)
<class 'int'>
輸出print()
>>> help(print)
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
print('A','B','C');print('D','E')
A B C
D E
print('A','B','C',end='--->');print('D','E')
A B C--->D E
print('A','B','C',sep='+')
A+B+C
print('A','B','C',sep='+',end='=')
A+B+C=
參數格式化:%
name="小明"
score=90
print("%3s 的成績 %2d 分" %(name,score))
王小明 的成績 90 分
參數格式化:format()
name="王小明"
score=90
print("{0:3s} 的成績 {1:2d} 分".format(name,score))
王小明 的成績 90 分
escape character
print("HelloWorld")
HelloWorld
print("Hello\'World") #單引號
Hello'World
print("Hello\"World") #雙引號
Hello"World
print("Hello\\World") #反斜線
Hello\World
print("Hello\nWorld") #換行
Hello
World
print("Hello\tWorld") #Tab鍵
Hello World
**********************************************************
python 撰寫風格
***********************************************************
#單行註解
''' 以下式多行註解
「;」
敘述很短時,可用半形分號,把多形敘述併成一行。
python 會在指令後,如:while 或 if ,以縮排表示程式區塊 CodeBlock (python 稱 Suite)。
「:」
半形冒號,提醒使用者下一行程式碼必須縮排,預設值則以一個「Tab」鍵,
即4個空白字元來完成縮排。
'''
x=6;y=9
if x<y:
print("正確")
else:
print("不正確")
----------------------------
正確
求二個正整數GCD
x=int(input("輸入第一個較大正整數:"))
y=int(input("輸入第二個較小正整數:"))
while x%y!=0:
x,y=y,x%y #2變數交換
else:
print("GCD={}".format(y))
===================== RESTART: C:/Users/User/Desktop/00.py
輸入第一個較大正整數:52
輸入第二個較小正整數:39
GCD=13
以自訂函式來完成
def myGCD(x,y):
while x%y!=0:
x,y=y,x%y #2變數交換
else:
return y
x=int(input("輸入第一個較大正整數:"))
y=int(input("輸入第二個較小正整數:"))
print("GCD={}".format(myGCD(x,y)))
===================== RESTART: C:/Users/User/Desktop/00.py
輸入第一個較大正整數:52
輸入第二個較小正整數:39
GCD=13