如何使用2个循环,如果为false,则无限期重复该程序

时间:2013-03-08 20:48:24

标签: python loops

现在我正在通过这个网站http://inventwithpython.com/chapter6.html

进行教程“Dragon Realm”

我明白这一切都在做些什么,但这不是我的问题。最后,我想添加一些代码,如果播放器说“不”,它说,就像我现在所说的那样,“太糟糕了 * !”然后回到程序的开头。我已经做到了这一点,但是一旦它经历了第二次,我得到的输入是你是否想要再次尝试是否输入是或否它只是结束程序。我尝试了while的多个组合,if / else,而True,而False,我没有得到我想要的结果。我不明白你是如何保持它继续前进的?这可能很简单,但我无法弄清楚。

这是该计划的代码。

import random
import time
def displayIntro():
    print('You are in a land full of dragons. In front of you,')
    print('you see two caves. In one cave, the dragon is friendly')
    print('and will share his treasure with you. The other dragon')
    print('is greedy and hungry, and will eat you on sight.')
    print()
def chooseCave():
    cave = ''
    while cave != '1' and cave != '2':
        print('Which cave will you go into? (1 or 2)')
        cave = input()
    return cave
def checkCave(chosenCave):
    print('You approach the cave...')
    time.sleep(2)
    print('It is dark and spooky...')
    time.sleep(2)
    print('A large dragon jumps out in front of you! He opens his jaws and...')
    print()
    time.sleep(2)
    friendlyCave = random.randint(1, 2)
    if chosenCave == str(friendlyCave):
        print('Gives you his treasure!')
    else:
        print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
    displayIntro()
    caveNumber = chooseCave()
    checkCave(caveNumber)
    print('Do you want to play again? (yes or no)')
    playAgain = input()

1 个答案:

答案 0 :(得分:1)

你可以简单地添加,

if 'n' in playAgain:
    print "too bad"
    playAgain = 'yes'

最后(在你的while循环中)

顺便说一句,这两行可以合并:

print('Do you want to play again? (yes or no)')
playAgain = input()

简单地说:

playAgain = input('Do you want to play again? (yes or no)')

因为input在请求输入时会显示字符串参数。