如何使用条件循环通过列表中的项目进行迭代?

发布于 2025-01-28 04:27:35 字数 420 浏览 2 评论 0原文

我正在尝试编写一个非常基本的代码,该代码可以将用户提供的输入和筛选通过积极响应的列表,以查看用户的响应是否属于该列表的一部分。 下面的代码迭代列表中的每个项目,但我不希望这样做,而是希望它检查列表中的所有项目并仅在输入在列表中时打印出某些内容。我该怎么做?

positive_responses = ['Good', 'Fine', 'Okay', 'Great']
user_response = input('How are you today? - ')
for each in positive_responses:
  if user_response == each:
    print('Glad to hear that')
  elif user_response != each:
    print('What can we do to help?')

I am trying to write a very basic code that can take the input given by a user and sift through a list of positive responses to see if the user's response is part of that list.
The code below iterates for each item in the list but I do not want that, instead I want it to check all items in the list and print out something only if the input is in the list. How can I do that?

positive_responses = ['Good', 'Fine', 'Okay', 'Great']
user_response = input('How are you today? - ')
for each in positive_responses:
  if user_response == each:
    print('Glad to hear that')
  elif user_response != each:
    print('What can we do to help?')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

意中人 2025-02-04 04:27:35

如果我正确理解您,则可以在操作员中使用

positive_responses = ["Good", "Fine", "Okay", "Great"]
user_response = input("How are you today? - ")

if user_response in positive_responses:
    print("Glad to hear that")
else:
    print("What can we do to help?")

prints(例如):

How are you today? - Great
Glad to hear that

If I understand you correctly you can use in operator:

positive_responses = ["Good", "Fine", "Okay", "Great"]
user_response = input("How are you today? - ")

if user_response in positive_responses:
    print("Glad to hear that")
else:
    print("What can we do to help?")

Prints (for example):

How are you today? - Great
Glad to hear that
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文