获取 if 语句以读取 raw_input 选择
Getting an if-statement to read the raw_input choice
我正在尝试编写一个小游戏,要求做出选择,然后根据所做的选择调用不同的函数。下面是我打开程序时调用的主要函数。
我的问题是,当程序运行并且我输入其中一个选项时,程序只会执行第一个 if-statement
。
因此,如果我将 2
或 school
放入 raw_input
或任何其他选项,我的程序仍会调用 work
函数。
def bedroom():
print "Good morning! Today is full of possibilities. What do you want to do?"
print """
1. Go to work
2. Go to school
3. Go on an adventure
4. Relax with a friend
"""
choice = raw_input("| ")
if "1" or "work" in choice:
print "Great! Making money and being diligent is a brilliant thing to do with life!"
work()
elif "2" or "school" in choice:
print "Wonderful! You can never learn enough."
school()
elif "3" or "adventure" in choice:
print "Oh, yay! Adventures make life exciting!"
adventure()
elif "4" or "relax" or "friend" in choice:
print "It's importanat to not exhaust yourself. Relaxing will help you refocus."
relax()
else:
print "Stop being creative! That wasn't an option."
bedroom()
关于为什么不考虑 if-else
声明的其余部分有什么想法吗?
这是因为 "1"
的计算结果为 True
。您的代码实际上在做
if ( "1" or ( "work" in choice ) ):
work()
你可能想做
if "1" in choice or "work" in choice:
work()
我正在尝试编写一个小游戏,要求做出选择,然后根据所做的选择调用不同的函数。下面是我打开程序时调用的主要函数。
我的问题是,当程序运行并且我输入其中一个选项时,程序只会执行第一个 if-statement
。
因此,如果我将 2
或 school
放入 raw_input
或任何其他选项,我的程序仍会调用 work
函数。
def bedroom():
print "Good morning! Today is full of possibilities. What do you want to do?"
print """
1. Go to work
2. Go to school
3. Go on an adventure
4. Relax with a friend
"""
choice = raw_input("| ")
if "1" or "work" in choice:
print "Great! Making money and being diligent is a brilliant thing to do with life!"
work()
elif "2" or "school" in choice:
print "Wonderful! You can never learn enough."
school()
elif "3" or "adventure" in choice:
print "Oh, yay! Adventures make life exciting!"
adventure()
elif "4" or "relax" or "friend" in choice:
print "It's importanat to not exhaust yourself. Relaxing will help you refocus."
relax()
else:
print "Stop being creative! That wasn't an option."
bedroom()
关于为什么不考虑 if-else
声明的其余部分有什么想法吗?
这是因为 "1"
的计算结果为 True
。您的代码实际上在做
if ( "1" or ( "work" in choice ) ):
work()
你可能想做
if "1" in choice or "work" in choice:
work()