首页 > 解决方案 > 如何使此函数中的代码重复?(Python)

问题描述

我正在编写一个游戏,我想要重做代码的某个部分。代码中的注释显示了我想要重做的内容。

import random
def getRandom():
    #this is the code I want to rerun (guess code) but I don't want to reset "players" and "lives"
    players = 10
    lives = 5
    myGuess = input("What number do you choose")
    compGuess = random.randint(1,5)
    compGuess = int(compGuess)
    print(f"Computer chose {compGuess}")
    if compGuess == myGuess:
        players = players - compGuess
        print(f"You took out {compGuess} players")
        print(f"There are {players} players left")
        #run guess code
    else:
        lives -= 1
        print(f"You lost a life! You now have {lives} lives remaining")
        #run guess
getRandom()

标签: pythonloops

解决方案


您需要添加一个循环。考虑一下您的循环条件是什么,以及循环内或循环外需要什么。我认为这样的东西是你正在寻找的。

import random
def getRandom():
     players = 10
     lives = 5
     while(lives > 0):
          myGuess = input("What number do you choose")
          compGuess = random.randint(1,5)
          compGuess = int(compGuess)
          print(f"Computer chose {compGuess}")
          if compGuess == myGuess:
              players = players - compGuess
              print(f"You took out {compGuess} players")
              print(f"There are {players} players left")
         else:
              lives -= 1
              print(f"You lost a life! You now have {lives} lives remaining")
getRandom()

推荐阅读