用書 PYTHON王者歸來 作者洪錦魁
text1 = “Tell me your name”
text2 = “press q to leave”
text = text1 + “\n” + text2 + “\n” + “=”
active = True
while active: input_text = input(text)
if input_text !=”q”:
print(input_text)
else:
active = False
執行結果
終極密碼
answer = 90
guess = 0
while guess!= answer:
guess = int(input(“Enter a numeber between 1-100:”))
if guess> answer:
print(“more smaller”)
elif guess< answer:
print(“more bigger”)
else:
print(“BINGO!”)
執行結果
Sentinel Value
number = int(input(“Please input a number:”))
sum = 0
while number:
sum+= number
number = int(input(“Please input a number”))
print(“Sum is “,sum)
執行結果
預測房價
house_price = 50000
future_price= 60000
year = 0
while house_price < future_price:
house_price = int(house_price * (1.01))
year +=
1print(f”目前房價50000,每年以10%速度增長的話,預計{year}年後會達到{future_price}”)
執行結果
While 巢狀
i = 1
while i<=9:
j = 1
while
j<=9:
result =i*j
print(f”{i}*{j}={result:<3d}”,end=” “)
j+= 1
print()
i += 1
執行結果
text1 = “Tell me your name”
text2 = “press q to leave”
text = text1 + “\n” + text2 + “\n” + “=”
while True:
input_text = input(text)
if input_text ==”q”:
break
else:
print(f”Hi {input_text.title()}”)
執行結果
若是print的地方沒有加title
有加title
title() 方法返回”標題化”的字符串,所有單字都是以大寫开始,其餘字母都小寫。
names=[“Lisa”,”Jenny”,”Jane”,”Kenny”,”Barbala”,”Susan”]
n=int(input(“Please input a numebr:”))
if n > len(names):
n = len(names)
index=0
while n < len(names):
if index ==n:
break
print(names[index],end=” “)
index+=1
執行結果
超過就印不出來
continue
index = 0
while index <=10:
index +=1
if index % 2:#若這邊是TRUE不執行print(index)
continue #不往下執行
print(index)
執行結果
While 迴圈 刪除集合內指定項目
Names = [“yamada”,”mori”,”mori”,”kazuya”,”yamakuchi”,”yoshimura”,”mori”]
Name = “mori”
print(f”刪除前{Names}”)
while Name in Names:
Names.remove(Name)
print(f”刪除後{Names}”)
執行結果
Fruits =[[“Apple”,1000],[“Banana”,600],[“Mango”,1200],[“peach”,2000],[“watermelon”,620]]
VIP = []
Students = []
while Fruits:
index_Fruits = Fruits.pop() #pop()删除数组的最后一个元素
if index_Fruits[1] >=1000:
VIP.append(index_Fruits)
else:
Students.append(index_Fruits)
print(f”VIP{VIP}”)
print(f”Students{Students}”)
#pop()
移除 list 中給定位置的項目,回傳。
如果沒有指定位置, Fruits.pop()
將會移除 list 中最後的項目並回傳
如果 Fruits 不是空串列,那就會一直執行,直到 Fruits.pop()
沒東西可以回傳
執行結果
enumerate 物件
一個可迭代的/可遍歷的物件(list、string)
enumerate會把它組成一個索引序列,利用它可以同時獲得索引和值enumerate
Names = [“yamada”,”mori”,”mori”,”kazuya”,”yamakuchi”,”yoshimura”,”mori”]
for Name in enumerate(Names):
print(Name)
for count,Name in enumerate(Names):
print(count,Name)
Names = [“yamada”,”mori”,”mori”,”kazuya”,”yamakuchi”,”yoshimura”,”mori”]
for Name in enumerate(Names,10):
print(Name)
for count,Name in enumerate(Names,10):
print(count,Name)
執行結果
印出叫MORI的人還有他的號碼’
Names = [“yamada”,”mori”,”mori”,”kazuya”,”yamakuchi”,”yoshimura”,”mori”]
index = 1
for name in Names:
if name == “mori”:
print(f”number:{index}:name:{name}”)
index += 1
執行結果
用enumerate 方法
Names = [“yamada”,”mori”,”mori”,”kazuya”,”yamakuchi”,”yoshimura”,”mori”]
for count,name in enumerate(Names,1):
if name == “mori”:
print(f”number:{count}:name:{name}”)
執行結果