Ask user to input a correct response in Python?
本问题已经有最佳答案,请猛点这里访问。
我是一个新手程序员,正在尝试编写一个程序,在这个程序中,我要求用户输入特定的信息,如奥巴马、克林顿或布什,并在他们给出正确答案时祝贺他们,或在他们给出错误答案时通知他们。
我很确定我犯了一个非常简单和愚蠢的错误,所以如果有人能帮助我,我会感激的。
1 2 3 4 5 6 7 8 9 | def main (): pres = input ('Please enter the surname of a recent President of the United States: ') if pres == 'Bush' or 'Obama' or 'Clinton': print('Great job! You know your stuff!') else: print('Sorry, that was incorrect.') main() |
谢谢您!
你有:
1 | if pres == 'Bush' or 'Obama' or 'Clinton': |
虽然这对人类有意义,但python认为你的意思是:
1 | if (pres == 'Bush') or ('Obama') or ('Clinton'): |
你需要明确你的意思:
1 | if pres == 'Bush' or pres == 'Obama' or pres == 'Clinton': |
但这是一口,所以你也可以这样做,这将检查
1 | if pres in {'Bush', 'Obama', 'Clinton'}: |
支票会员资格的最佳选择是使用具有
1 | if pres in {'Bush','Obama','Clinton'} |
从python wiki:
The sets module provides classes for constructing and
manipulating unordered collections of unique elements. Common uses
include membership testing, removing duplicates from a sequence,
and computing standard math operations on sets such as intersection,
union, difference, and symmetric difference.
你应该这样做:
1 | if pres == 'Bush' or pres == 'Obama' or pres == 'Clinton': |