今天開始將進行Python基本語法練習,因大部分語法跟很多程式語言相似,故這個部分將主要以筆記方式註記重點,做為未來的備忘錄。
補充說明:部分範例程式來自於W3Schools。
if 2>1:
print("2>1")
print("First Part")
else:
print("Else Part")
#This is a comment
"""
Comment 1
Comment 2
Comment 3
"""
x = 4
y = "Test"
print(type(x))
print(type(y))
x = 4
print(type(x))
x = "Test"
print(type(x))
x = str(1)
print(type(x))
x = int(1)
print(type(x))
x = float(1)
print(type(x))
x, y, z = "A", "B", "C"
x = y = z = "A"
testSet = ["A","B","C"]
x, y, z = testSet
Text Type:str
Numeric Types:int, float, complex
x = 1 # 數值
y = "j" # 文字
z = 1j # 複合型態
print(type(x))
print(type(y))
print(type(z))
x = ["A","B","C"] # list
y = ("A","B","C") # tuple
z1 = range(1, 7) # range
z2 = range(7) # range
employee = {"id": 1, "name": "Alice"}
print(employee)
print(employee["name"])
x = {"A","B","C"} # set
x = frozenset({"A","B","C"}) # frozenset
x = True
y = False
使用bool()可以將各種型態的變數轉換為bool型態。
判斷為False的情境:
需要使用Random模組
import random
print(random.randrange(1,10))
因重點較多故另外整理出來。
x = """Line 1.
Line 2.
Line 3.
"""
y = '''Line 4.
Line 5.
Line 6.
'''
print(x)
print(y)
a = "Test"
print(len(a))
x = "Hello World"
print("World" in x)
x = "Hello World"
print(x[2:5])
print(x[:5])
print(x[2:])
print(x[-5:-2])
x = " Hello World !"
print(x.lower()) # 轉換為小寫
print(x.upper()) # 轉換為大寫
print(x.strip()) # 移除頭尾的空白
print(x.replace("l", "L")) # 取代
print(x.split(" ")) # 字串分隔
x = "Hello "
y = "World"
z = x + y
print(z)
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
可以使用index來指定欲取代的變數。
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))