賴昱錡
討厭程式的小廢物
賴昱錡
環境建置、第一支程式
python filename.py
print('Hello World!')
# 這是註解啦
# 上方的程式碼代表輸出Hello World並換行
恭喜你撰寫完 Python 的第一支程式!
我要怎麼像 C++ 一樣輸入呢?
name = input("hi, how may i call you?")
print("Hello, "+name)
# 將輸入的東西存入 name ,印出 Hello, name
# input()中的字串,有點像輸入前顯示的字串
#,沒什麼用
變數與他的快樂夥伴
number = 7122
# 整數
sentence = "Hello world!"
# 字串
float_num = 7.122
# 小數
flag = True
# 布林值 (邏輯)
print(type(sentence))
# 印出變數的型別
當我們寫:
number = 7122
時,
代表我們為 number 賦值7122,存入記憶體中
Python 的變數不需宣告型別,且可重複使用
a = 765 * 432 + 9900
# +-*/分別代表著加、減、乘、除
# //代表除之後,取整數
b = 2022
b += a
# 宣告變數 b = 2022,再把 b 的值加上 a。
print(b>=a)
# 輸出的為b>=a的布林值,
# <、>、<=、==、>=
條件與迴圈
a = 33
b = 200
if b > a:
print("b is greater than a")
# 注意縮排!
password = "infor35th7122"
if input("請輸入密碼!") != password:
print("logged in!")
else:
print("QQ")
# 注意縮排!
score = 72
if score>=90:
print("ORZ")
elif score>=60:
print("pass")
elif score>=40:
print("非常好補考")
else:
print("我很喜歡重補修,但是...")
if statement:
blablabla
代表statement如果
為真,則執行下方的扣
elif等同於c++的else if
若上個if/elif中不成立,
改執行該elif中的扣
都不成立
執行else中的內容
for i in range(10):
print(i)
# 從0數到9,並印出來
n = int(input())
while n>=0:
n = n-5
print(n)
# 當n>=0這個statement為True時
# ,會重複執行冒號下的部分
lessons = ["Chinese","English","math",
"computer","society","science"]
for class in lessons:
print(class,end=",")
# 遍歷陣列 lessons 中的內容 (等等會講)
比較需要提的:
range(n)
: 從0數到n-1range(s,e)
: 從s數到e-1range(s,e,d)
: 從s數到e-1,間隔為d。(若d為負,則倒著數)陣列跟函式
cars = ["Ford", "Volvo", "BMW"]
fruit = ["Apple","Orange",7122,
True,"Watemelon","etc"]
# 宣告方式
print(cars[2])
# 印出BMW
print(fruit[6])
# 出錯了,並沒有第6項
若我們想擷取特定的片段?
==> arrayname[起始項:最終項:間隔]
# EX
print(arrayname[4:0:-1])
# 陣列長度
print(len(cars))
a = [99,1,2,3,4,5,6,7,8]
for i in a:
print(i)
a.append(7122)
# 從後方加入7122,
# [99,1,2,3,4,5,6,7,8,7122]
a.pop(1)
# 移除a[1]
# [99,2,3,4,5,6,7,8,7122]
a.remove(5)
# 移除a[5]
# [99,2,3,4,5,7,8,7122]
a.sort()
# 排序該list
# [2,3,4,5,7,8,99,7122]
def hello():
print("Hello INFOR!")
hello()
#呼叫一個函式
def add_three(a,b,c):
return a+b+c
# 括號中的a,b,c叫做參數,可以傳入函式中進行許多事情
print(add_three(12,15,34))
# a=12,b=15,c=34傳入add_three中,回傳a+b+c
def sumNumber(*params):
total = 0
for param in params:
total +=param
return total
# 不定數目參數
def rightFunction(first, second = 12):
return first
def wrongFunction(first=12, second):
# 出錯 non-default argument follows default argument
return first
# 函示也可以宣告預設值
除此之外, Python也有許多內建函式
如: pow(a,b)、round()、sum
print('OwO')
By 賴昱錡
家教 - Python基礎