我可以让变量在 If 语句中工作吗?[复制]

Can i make variables work within If statements? [duplicate]

提问人:Gustavo Saldan 提问时间:5/28/2023 更新时间:5/28/2023 访问量:48

问:

如何使此变量与python中的if语句一起使用?

arrived = input('Have the doorbell ringed?: ')

if arrived == 'yes' or 'Yes':
    doorbell = input('Is it from ifood?: ')
elif arrived == 'no' or 'No':
    print('It is not here yet, keep waiting')
else:
    print('Please answer the first question with yes or no')

if doorbell == 'yes' or 'Yes':
    print('Your ifood have arrived!!!')
elif doorbell == 'no' or 'No':
    print('It is not your ifood yet, keep waiting')
else:
    print('Please answer the questions with yes or no')

我是一个初学者,这是从练习开始的,我已经搜索了一段时间,我知道变量在 python 中是全局的,但有没有办法让它工作?

python if-statement 变量

评论

0赞 marmeladze 5/28/2023
设置在脚本的开头。doorbell = None

答:

0赞 Erwin Kalvelagen 5/28/2023 #1

你错了。更好的是:if

  if arrived == 'yes' or arrived == 'Yes':

  if arrived in ['yes','Yes']:

评论

0赞 Gustavo Saldan 5/28/2023
第二个要求在逗号后留一个空格,但它对 IFS 有效,谢谢!
1赞 Erwin Kalvelagen 5/28/2023
第二个要求在逗号后留一个空格无法重现。
0赞 Redz 5/28/2023 #2

首先,你的 if 语句是错误的 - 它需要包含第二个,否则它将不起作用。它应该看起来像这样。arrived ==

if arrived == 'yes' or arrived == 'Yes':

其次,您可能希望在第一个 if 语句中加入第二个 if-elif-else,因为只有在满足 if 语句条件时才应触发它。

完整解决方案:

arrived = input('Have the doorbell ringed?: ')

if arrived == 'yes' or arrived == 'Yes':
    doorbell = input('Is it from ifood?: ')
    if doorbell == 'yes' or 'Yes':
        print('Your ifood have arrived!!!')
    elif doorbell == 'no' or 'No':
        print('It is not your ifood yet, keep waiting')
    else:
        print('Please answer the questions with yes or no')
elif arrived == 'no' or arrived == 'No':
    print('It is not here yet, keep waiting')
else:
    print('Please answer the first question with yes or no')

评论

0赞 Matthias 5/29/2023
或者做,只是要求.现在您可以输入“是”或“是”或“是”或“yeS”......arrived = input('Have the doorbell ringed?: ').lower()if arrived == 'yes':