[英]How to use an if statement in a loop
我有一個簡單的例子。 我將 name 傳遞給 serv 並遍歷字典。 所以當我給 serv 一個名字時它應該在循環中打印出來,但我不知道為什么 else 正在打印
我的代碼:
service = {
"item1": 22,
"item2": 31,
}
def serv(**name):
selctser = input("pls select your services: ")
for ss, sprice in name.items():
if selctser in ss:
print (f"Your Services is: {selctser}, and Price is => {sprice}")
else:
print('Select good value')
allwoedname = ["n1", "n2"]
name = input("Please enter ur name: ")
if name in allwoedname :
print("Welcone to store booking")
else:
print("You dont have a login info")
serv(**service)
我對您的代碼進行了一些重構以提高可讀性:
service = {
"item1": 22,
"item2": 31}
def serv(services: dict):
selected_service = input("PLease select your services: ")
for ss, price in services.items():
if selected_service in ss:
print(f"Your Services is: {selected_service}, and Price is => {price}")
else:
print('Select good value')
allowed_names = ["n1", "n2"]
name = input("Please enter ur name: ")
if name in allowed_names:
print("Welcone to store booking")
else:
print("You dont have a login info")
serv(service)
讓我們嘗試將“n1”作為名稱傳遞,將“item2”作為服務傳遞。 控制台將返回:
Please enter ur name: n1
Welcone to store booking
PLease select your services: item2
Select good value
Your Services is: item2, and Price is => 31
讓我們更改服務字典:
service = {
"item1": 22,
"item2": 31,
"item3": 11,
"item4": 28}
現在我要給出錯誤的名稱和 item3,這就是控制台打印的內容:
Please enter ur name: Some name
You dont have a login info
PLease select your services: item3
Select good value
Select good value
Your Services is: item3, and Price is => 11
Select good value
如您所見,如果 name 的條件正常工作。 但是服務條件現在打印 4 次 - 3 次條件未滿足,1 次為真。
這是因為您使用服務迭代 dict 並檢查每次迭代的語句。 如果我理解你的意圖正確,你應該這樣做:
def serv(services: dict):
selected_service = input("PLease select your services: ")
if selected_service in services.keys():
print(f"Your Services is: {selected_service}, and Price is => {services[selected_service]}")
else:
print('Select good value')
Output:
Please enter ur name: n2
Welcone to store booking
PLease select your services: item2
Your Services is: item2, and Price is => 31
編輯:我忘了提 - 在 arguments 之前不需要使用 **,因為你知道會有多少 arguments 存在。
它的工作沒有循環,實際上我對為什么代碼不能使用循環感到困惑,所以我在這里循環進入鍵和值
for ss, sprice in name.items():
並詢問輸入是否在 ss <- Key
if selctser in ss:
所以從 Value 中打印輸入和價格
print (f"Your Services is: {selctser}, and Price is => {sprice}")
這就是其他
else: print('Select good value')
為什么我得到錯誤或以各種方式打印!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.