gpt4 book ai didi

python - 如果在 for 循环中没有匹配项,如何打印出特定的消息

转载 作者:行者123 更新时间:2023-12-03 21:13:49 25 4
gpt4 key购买 nike

我的问题是如果在 for 循环中没有匹配的东西,如何打印出来。例如:

a = {'store' : 'A', 'menu' : 'pizza', 'price' : 20000}
b = {'store' : 'B', 'menu' : 'chicken', 'price' : 18000}
c = {'store' : 'C', 'menu' : 'noodle', 'price' : 5000}
d = {'store' : 'D', 'menu' : 'sushi', 'price' : 15000}
e = {'store' : 'E', 'menu' : 'chicken', 'price' : 23000}
f = {'store' : 'F', 'menu' : 'pork', 'price' : 30000}

Total = [a, b, c, d, e, f]

l = input('what food?: ')
p = int(input('how much you want to spend? '))

for i in range(5):
if Total[i]['menu'] == l and int(Total[i]['price']) <= p:
print('menu', Total[i]['store'], 'price', Total[i]['price'])

循环后,如果没有这样的商店满足条件,我想打印出 'There is no store' .

最佳答案

只需添加一个 bool 值来检查是否找到了价格。

a = {'store' : 'A', 'menu' : 'pizza', 'price' : 20000}
b = {'store' : 'B', 'menu' : 'chicken', 'price' : 18000}
c = {'store' : 'C', 'menu' : 'noodle', 'price' : 5000}
d = {'store' : 'D', 'menu' : 'sushi', 'price' : 15000}
e = {'store' : 'E', 'menu' : 'chicken', 'price' : 23000}
f = {'store' : 'F', 'menu' : 'pork', 'price' : 30000}

Total = [a, b, c, d, e, f]

l = input('what food?: ')
p = int(input('how much you want to spend? '))

found = False
for i in range(5):
if Total[i]['menu'] == l and int(Total[i]['price']) <= p:
print('menu', Total[i]['store'], 'price', Total[i]['price'])
found = True

if not found:
print ("No stores were found.")

关于python - 如果在 for 循环中没有匹配项,如何打印出特定的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61882322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com