如何重复我的程序而不重复

时间:2017-01-28 20:42:37

标签: python python-3.6

我试图找出如何重复我的程序(代码)而不重复,但我读过的所有答案都没有意义。有人可以帮助我吗? 这是我正在研究的程序

import random
words=['hello','run','apple','day','month','cat','dog','bird','car','water']
word=random.choice(words)
length=len(word)
life=50
print('\t\tGuess the word!')
print('instructions: Guess the word. The word is only written by the alphabets.')
pn=input('Type your player name :')
print('Use this to help you! :',words)
print('The length of the word is',length,'letters')
fl=input('Guess the first letter of the word! :')
if fl==word[0]:
    print('Whoah! Nice guess',pn)
else:
    life=life-1
    print('Nice guess but wrong. Try again! You have',life,'lives left!')

3 个答案:

答案 0 :(得分:0)

执行具有永久True条件的while循环

只需在代码中添加 while(True):即可让该代码段永久运行...

import random

while(True):
    words=['hello','run','apple','day','month','cat','dog','bird','car','water']
    word=random.choice (words)
    length=len(word)
    life=50
    print('\t\tGuess the word!')
    print('instructions: Guess the word. The word is only written by the alphabets.')
    pn=input('Type your player name :')
    print('Use this to help you! :',words)
    print('The length of the word is',length,'letters')
    fl=input('Guess the first letter of the word! :')
    if fl==word[0]:
        print('Whoah! Nice guess',pn)
    else:
        life=life-1
        print('Nice guess but wrong. Try again! You have',life,'lives left!')

答案 1 :(得分:0)

我不确定我是否理解正确,但您可以添加一个布尔值正确与否,并使用while循环继续循环直到给出正确的答案。 这样的事情可能就是:

while incorrect:
    run
    loop
answer is correct

循环内的代码应该缩进。

答案 2 :(得分:0)

我相信这就是你要做的事情:

import random

life=50
words=['hello','run','apple','day','month','cat','dog','bird','car','water']
print('\t\tGuess the word!')
print('instructions: Guess the word. The word is only written by the alphabets.')
pn=input('Type your player name :')
print('Use this to help you! : {0}'.format(words))

while life:
    word=random.choice(words)
    length=len(word)
    print('The length of the word is {0} letters'.format(length))
    fl=input('Guess the first letter of the word! :')
    if fl==word[0]:
        print('Whoah! Nice guess {0}'.format(pn))
    else:
        life=life-1
        print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))