此代碼應該給出一條錯誤訊息,“錯誤請重試!” 如果輸入的顏色不是紅色、藍色或黃色。它給了我錯誤訊息,同時也給了我正確的輸入,我不知道為什么。
ColorOne = input('Enter the first primary color please ')
ColorTwo = input('Enter the second primary color please ')
if ColorOne != ('red' or 'blue' or 'yellow'):
print('Error please try again!')
if ColorTwo != ('red' or 'blue' or 'yellow'):
print('Error please try again!')
if ColorOne == ('red') and ColorTwo == ('blue'):
print('Purple')
if ColorOne == ('red') and ColorTwo == ('yellow'):
print('Orange')
if ColorOne == ('blue') and ColorTwo == ('yellow'):
print('Green')
if ColorTwo == ('red') and ColorOne == ('blue'):
print('Purple')
if ColorTwo == ('red') and ColorOne == ('yellow'):
print('Orange')
if ColorTwo == ('blue') and ColorOne == ('yellow'):
print('Green')
uj5u.com熱心網友回復:
嘗試這個:
ColorOne = input('Enter the first primary color please ')
ColorTwo = input('Enter the second primary color please ')
if ColorOne not in ['red','blue','yellow']:
print('Error please try again!')
if ColorTwo not in ['red','blue','yellow']:
print('Error please try again!')
if ColorOne == ('red') and ColorTwo == ('blue'):
print('Purple')
if ColorOne == ('red') and ColorTwo == ('yellow'):
print('Orange')
if ColorOne == ('blue') and ColorTwo == ('yellow'):
print('Green')
if ColorTwo == ('red') and ColorOne == ('blue'):
print('Purple')
if ColorTwo == ('red') and ColorOne == ('yellow'):
print('Orange')
if ColorTwo == ('blue') and ColorOne == ('yellow'):
print('Green')
您的代碼的問題在于邏輯,在現實世界(口語)中,您會說如果顏色不是紅色、藍色或黃色,則執行某些操作,但在編程邏輯中,這不會像那樣作業。!= (紅色或藍色或黃色)等于如果顏色不是紅色而不是藍色而不是黃色,則執行某些操作。這就是使用德摩根定律。
uj5u.com熱心網友回復:
解決了。
ColorTwo = input('Enter the second primary color please ')
if ColorOne not in ('red', 'blue', 'yellow'):
print('Error please try again!')
if ColorTwo not in ('red', 'blue', 'yellow'):
print('Error please try again!')
if ColorOne == ('red') and ColorTwo == ('blue'):
print('Purple')
if ColorOne == ('red') and ColorTwo == ('yellow'):
print('Orange')
if ColorOne == ('blue') and ColorTwo == ('yellow'):
print('Green')
if ColorTwo == ('red') and ColorOne == ('blue'):
print('Purple')
if ColorTwo == ('red') and ColorOne == ('yellow'):
print('Orange')
if ColorTwo == ('blue') and ColorOne == ('yellow'):
print('Green')
你需要像這樣檢查
if ColorTwo not in ('red', 'blue', 'yellow'):
uj5u.com熱心網友回復:
問題是代碼ColorOne != ('red' or 'blue' or 'yellow'):。檢查變數是否是這些值之一不是正確的方法。你應該改為ColorOne not in ('red', 'blue', 'yellow'):
無論如何,我做了一些改進。
ColorOne = input('Enter the first primary color please ')
ColorTwo = input('Enter the second primary color please ')
Colors = ('red','blue','yellow')
combination = set((ColorOne.strip().lower(), ColorTwo.strip().lower()))
if not combination.issubset(Colors):
print('Error please try again!')
elif combination == {'blue','red'}:
print('Purple')
elif combination == {'red','yellow'}:
print('Orange')
elif combination == {'blue','yellow'}:
print('Green')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/437118.html
上一篇:XPath案例/IfElse函式
