繁体   English   中英

如何在循环中使用 if 语句

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM