python - 尝试在 while 循环中设置 "wrong key pressed"错误

标签 python python-2.7

所以我正在通过“Learn Python The Hard Way”来学习 Python, 我目前正在写一个简单的文本冒险。

我的问题出在代码的“战斗”部分(如下所示)。只有数字 1 和 2 需要由用户按下。如果按下不同的 int ,它会正确地抛出“抱歉,不明白”,但如果按下一个字母,它就会崩溃并退出,并说(非常正确)它正在等待一个 int 。显然我的问题是,如何将其设置为期望两者,并在按下字母时抛出错误?

提前致谢:)

        while True:
            player_dmg = randint(1, 10)
            enemy_dmg = randint(1, 10)

            if enemy_hp < 0:
                os.system('clear')
                print "[ENEMY NUTRALISED]"
                print
                print hit_e
                raw_input()
                return 'forth_area'
            elif player_hp < 0:
                return 'death'

            else:
                print "[COMBAT OPTIONS]"
                print "1. Attack"
                print "2. Defend"
                print
                choice = raw_input("*>>*")
                choice = int(choice)
                print
            if choice == 1:
                enemy_hp = enemy_hp - player_dmg
                print "[ENEMY STATUS: %d]" % enemy_hp
                print "[DAMAGE DONE: %d]" % player_dmg
                print
                player_hp = player_hp - enemy_dmg
                print "[DAMAGE RECIVED: %d]" % enemy_dmg
                print "[CURRENT STATUS: %d]" % player_hp
            elif choice  == 2:
                enemy_hp = enemy_hp - player_dmg / 2
                print "[ENEMY STATUS %d]" % enemy_hp
                print "[DAMAGE DONE %d]" % player_dmg
                print
                player_hp = player_hp - enemy_dmg
                player_hp = player_hp + 3
                print "[DAMAGE RECIVED: %d]" % enemy_dmg
                print "[CURRENT STATUS: %d]" % player_hp
                print
            else:
                print no_understand

最佳答案

你有:

choice = raw_input("*>>*")
choice = int(choice)
# . . .
if choice == 1:
# . . .
elif choice == 2:

最简单的修复方法是使用:

choice = raw_input("*>>*")
# . . .
if choice == '1':
# . . .
elif choice == '2':

raw_input 返回一个字符串。为什么要转换成数字呢?只需测试文本 '1''2' 等。它还可以更轻松地添加字符命令(例如 'q'退出)。

关于python - 尝试在 while 循环中设置 "wrong key pressed"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14665674/

相关文章:

python - 如何使用Python Pillow/Image将小图像插入照片的一角?

python - 替换字符串中的货币值时,Python 中的 re.sub() 并不总是有效

python - 试图找到所有可能的组合和分组

python - 如何将嵌套字典转换为数据框?

python - 在使用 For 形成的数组中包含 If

python - 'WSGIRequest' 对象没有属性 'user' Django admin

python-2.7 - ifilter怎么了?

Python字典查找返回多个结果?

python - 从 BeautifulSoup 中的 findall() 检索 href 的子集

python - 将 Sage 矩阵赋值给 R 中的变量