用書 PYTHON王者歸來 作者洪錦魁
加上文字做列印
Cowokers = [“Nini”,”Sara”,”Jhon”,”Kiki”]
for cowoker in Cowokers:
print(cowoker)
print(f”{cowoker.title()},My cowkers are “)
print(f”My cowkers are,{cowoker.title()}”)

執行結果

列印出前三位或後三位
Cowokers = [“Nini”,”Sara”,”Jhon”,”Kiki”]
for cowoker in Cowokers[:3]:
print(cowoker)
for cowoker in Cowokers[-3:]:
print(cowoker)

執行結果

印出字尾或字首相同的串列
files = [“01.py”,”05.js”,”03.html”,”06.css”]
py = []
for file in files:
if file.endswith(“.py”):
py.append(file)
print(py)
names = [“sakamoto kulumi”,”sakamoto shingo”,”hayashi sueo”,”yoshimura shingo”]
sakamoto = []
for name in names:
if name.startswith(“sakamoto”):
sakamoto.append(name)
print(sakamoto)

執行結果

刪除重複
drink1 = [“milk”,”water”,”juice”,”bear”,”black tea”]
drink2 = [“juice”,”bear”,”cock”,”green tea”,”sake”]
print(f”drink2{drink2}”)
for drink in drink2[:]: 如果沒有 [:]這個的話 就只會找出一個, 加了 [:]可以找出全部
if drink in drink1:
drink2.remove(drink)
print(f”{drink}”)
print(f”drink2{drink2}”)

執行結果
如果沒有 [:]這個的話就只會找出一個,

加了 [:]可以找出全部

RANGR
n = int(input(“Please input a number:”))
for number in range(n):
print(“*”,end=””)

執行結果

如果刪掉 end=”” 則會印出以下

算出存款複利
money = 5000
rate = 0.015
n = 5
for i in range(n):
money*= (1 + rate)
print(f”第{i+1}年本金和:{int(money)}”)

執行結果

3個參數的range()
#range(start,end,step)
for x in range(3,9,5):
print(x)

執行結果

0+…n的總和
n = int(input(“Please input a number:”))
sum = 0
for number in range(1,n+1):
sum += number
print(f”SUM= {sum}”)

執行結果

n = int(input(“Please input a number:”))
total = sum(range(n+1))
print(“Total”,total)

執行結果

平方串列
NUMBER = []
n =eval(input(“Please input a numebr:”))
if n>10 : n = 10
for num in range(1,n+1):
value = num*num
NUMBER.append(value)
print(NUMBER)

執行結果

n =int(input(“Please input a numebr:”))
if n>10 : n = 10
NUMBER =[num**2 for num in range(1,n+1)]
print(NUMBER)

執行結果

刪除回圈內的質
Foods = [“rise”,”bread”,”candy”,”cookies”]
for food in Foods[:]:
Foods.remove(food)
print(“remove”,{food})
print(Foods)

執行結果

List自動生成
number = []
for n in range(3,20,2):
number.append(n)
print(number)

執行結果

number = [n for n in range(3,20,2)]
print(number)

執行結果

a**2+b**2 ==c**2
#a**2+b**2 ==c**2
ANS = [[a,b,c] for a in range(1,20) for b in range(a,20) for c in range(b,20)
if a**2 + b**2 == c**2]
print(ANS)

執行結果

LIST UNPACKING
Familes = [“Father”,”Mather”,”Uncle”,”Ant”,”Grandpa”,”Grandmon”]
Names = [“Allen”,”Smith”,”Mike”]
result =[[Family,Name] for Family in Familes for Name in Names]
print(result)for Family,Name in result:
print(Family,Name)

執行結果
