否则,elif,如果Python出现问题 [英] Else, elif, if problems in Python
问题描述
instrument=(raw_input("Which kind of tab would you like to view? Enter 'Guitar' or 'Bass' for a random tab " ))
print
if instrument=='guitar' or 'Guitar':
print ("0-3-5---0-3-6-5---0-3-5-3-0")
elif instrument=='bass' or 'Bass':
print ("3-5-12--12-0-5-6-0-0-0-3")
else:
print 'Sorry, please re-enter a proper answer'
此代码无论你为变量'乐器'键入什么,每次打印出'吉他'选项卡(第一个if语句)。
This code prints out the 'guitar' tab(the first if statement) every time, no matter what you type in for the variable 'instrument'.
我正在尝试教我自己蟒蛇,我只是跳进去学习,这是我正在努力的基本程序,并希望扩展。
I'm trying to teach myself python and am just jumping in and learning as I go, this is a basic program I'm working on and want to expand on.
我看过网上但是从我读过的关于if else语句的内容来看,我的新手眼睛看起来这个代码应该有效。我错过了一些我无法弄清楚的东西
I've looked online but from what I've read about if else statements, it looks to my novice eyes that this code should work. I'm missing something that I just can't figure out
推荐答案
if instrument=='guitar' or 'Guitar':
被解析为
if (instrument=='guitar') or ('Guitar'):
'Guitar'
等非空字符串被评估为 True
,所以第一个条件总是 True
。
Non-empty strings like 'Guitar'
are evaluated as True
, so the first condition is always True
.
相反,请使用
if instrument in ('guitar', 'Guitar'):
或者,如果您愿意接受有趣的拼写,例如'gUiTAR'
,您可以使用
or, if you are willing to accept funny spellings like 'gUiTAR'
, you could use
if instrument.lower() == 'guitar':
这篇关于否则,elif,如果Python出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!