簡體   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