【问题标题】:How to repeat my program without duplicating如何在不重复的情况下重复我的程序
【发布时间】:2017-01-28 20:42:36
【问题描述】:

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

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!')

【问题讨论】:

  • 你听说过循环吗?
  • 这些答案的哪一部分没有意义?您很可能只会收到相同的答案

标签: python python-3.6


【解决方案1】:

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

只需在代码中添加 while(True): 即可使 sn-p 永远运行...

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!')

【讨论】:

    【解决方案2】:

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

    while incorrect:
        run
        loop
    answer is correct
    

    循环内的代码应该缩进。

    【讨论】:

      【解决方案3】:

      我相信这就是你想要做的:

      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))
      

      【讨论】:

        猜你喜欢
        • 2015-08-17
        • 2012-10-23
        • 1970-01-01
        • 2022-01-13
        • 2022-01-20
        • 2021-07-12
        • 2014-08-25
        • 2014-07-31
        相关资源
        最近更新 更多