要求用户在 Python 中输入正确的答案?
Ask user to input a correct response in Python?
我是一名新手程序员,我正在尝试编写一个程序,我要求用户提供特定的输入,例如奥巴马、克林顿或布什,并在他们给出正确答案时祝贺他们,或在他们给出错误答案时通知他们.
我很确定我犯了一个非常简单和愚蠢的错误,所以如果有人能帮助我,我将不胜感激。
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()
谢谢!
你应该这样做:
if pres == 'Bush' or pres == 'Obama' or pres == 'Clinton':
你有:
if pres == 'Bush' or 'Obama' or 'Clinton':
虽然这对人类来说很有意义,但 Python 认为你是这个意思:
if (pres == 'Bush') or ('Obama') or ('Clinton'):
'Obama'
和 'Clinton'
是非空字符串,因此它们始终为真,因此整个表达式始终为真,并且您输入的内容没有任何区别。
您需要明确说明您的意思:
if pres == 'Bush' or pres == 'Obama' or pres == 'Clinton':
但这有点啰嗦,所以你也可以这样做,这将检查 pres
是否在正确答案集中:
if pres in {'Bush', 'Obama', 'Clinton'}:
检查成员资格的最佳选择是使用具有 O(1)
的 set
,因此您可以使用以下内容代替 if
语句:
if pres in {'Bush','Obama','Clinton'}
来自 python 维基:
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.
我是一名新手程序员,我正在尝试编写一个程序,我要求用户提供特定的输入,例如奥巴马、克林顿或布什,并在他们给出正确答案时祝贺他们,或在他们给出错误答案时通知他们.
我很确定我犯了一个非常简单和愚蠢的错误,所以如果有人能帮助我,我将不胜感激。
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()
谢谢!
你应该这样做:
if pres == 'Bush' or pres == 'Obama' or pres == 'Clinton':
你有:
if pres == 'Bush' or 'Obama' or 'Clinton':
虽然这对人类来说很有意义,但 Python 认为你是这个意思:
if (pres == 'Bush') or ('Obama') or ('Clinton'):
'Obama'
和 'Clinton'
是非空字符串,因此它们始终为真,因此整个表达式始终为真,并且您输入的内容没有任何区别。
您需要明确说明您的意思:
if pres == 'Bush' or pres == 'Obama' or pres == 'Clinton':
但这有点啰嗦,所以你也可以这样做,这将检查 pres
是否在正确答案集中:
if pres in {'Bush', 'Obama', 'Clinton'}:
检查成员资格的最佳选择是使用具有 O(1)
的 set
,因此您可以使用以下内容代替 if
语句:
if pres in {'Bush','Obama','Clinton'}
来自 python 维基:
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.