如何重新开始简单的投币游戏

时间:2010-12-29 19:51:23

标签: python

我正在使用python 2.6.6

我只是想从一开始就根据用户输入重启程序。 感谢

import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
    chance = random.choice(['heads','tails'])
    person = raw_input(" heads or tails: ")
    print "*You have fliped the coin"
    time.sleep(1)
    if person == 'q':
         print " Nooo!"
    if person == 'q':
        break   
    if person == chance:
        print "correct"
    elif person != chance:
        print "Incorrect"
        guess -=1
    if guess == 0:
        a = raw_input(" Play again? ")
        if a == 'n':
            break
        if a == 'y':
            continue

#Figure out how to restart program

我对continue语句感到困惑。 因为如果我继续使用,我在第一次输入“y”后就永远不会选择“再次播放”。

4 个答案:

答案 0 :(得分:2)

在您希望重新启动循环的位置使用continue语句。就像您使用break来断开循环一样,continue语句将重新启动循环。

不是基于您的问题,而是如何使用continue

while True: 
        choice = raw_input('What do you want? ')
        if choice == 'restart':
                continue
        else:
                break

print 'Break!' 

此外:

choice = 'restart';

while choice == 'restart': 
        choice = raw_input('What do you want? ')

print 'Break!' 

输出

What do you want? restart
What do you want? break
Break!

答案 1 :(得分:1)

我建议:

  1. 将您的代码分解为函数;它使它更具可读性
  2. 使用有用的变量名称
  3. 不消耗你的常量(第一次通过你的代码后,你怎么知道开始有多少猜测?)
  4. import random
    import time
    
    GUESSES = 5
    
    def playGame():
        remaining = GUESSES
        correct = 0
    
        while remaining>0:
            hiddenValue = random.choice(('heads','tails'))
            person = raw_input('Heads or Tails?').lower()
    
            if person in ('q','quit','e','exit','bye'):
                print('Quitter!')
                break
            elif hiddenValue=='heads' and person in ('h','head','heads'):
                print('Correct!')
                correct += 1
            elif hiddenValue=='tails' and person in ('t','tail','tails'):
                print('Correct!')
                correct += 1
            else:
                print('Nope, sorry...')
                remaining -= 1
    
        print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
    
    def main():
        print("You may press q to quit at any time")
        print("You have {0} chances".format(GUESSES))
    
        while True:
            playGame()
            again = raw_input('Play again? (Y/n)').lower()
            if again in ('n','no','q','quit','e','exit','bye'):
                break
    

答案 2 :(得分:0)

您需要使用random.seed初始化随机数生成器。如果每次都使用相同的值调用它,则random.choice中的值将重复。

答案 3 :(得分:0)

输入'y'后,guess == 0永远不会为真。