繁体   English   中英

如何使此函数中的代码重复? (Python)

[英]How do I make code in this function repeat? (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()

是的,我认为你应该先创建一个心智模型。

你想发生什么以及你希望它如何发生。

如果你想“重做”一些东西,这听起来像是一个循环,试着在它自己的一端创建一个“自调用”的函数,并有一种退出的方式。

如果你创建了一个函数,你可以在它自身内部调用它。

例子:

def testfunction(value):
    a = value
    b = 2
    c = a + b
    testfunction(c)

但是添加一些摆脱这个循环的方法会很有趣..

您需要添加一个循环。 想一想你的循环条件是什么以及循环内或循环外需要什么。 我认为这样的事情就是你正在寻找的。

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

由于您不想重置players 和lives 变量,您可以在函数外部将其声明为全局变量。每个函数都将拥有该变量的相同副本,因此您不会重置它。 如需更多参考,您可以查看此处: https : //www.w3schools.com/python/gloss_python_global_variables.asp以了解有关全局变量的更多信息。 正如 Ngeorg 提到的,您需要有一个循环和某种条件来重新运行代码并在适当的时间停止它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM