简体   繁体   中英

How do I make code in this function repeat? (python)

I am writing a game and I want a certain part of the code to redo. The comments in the code show what I want to redo.

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

Yeah, I think you should create a mental model first.

What do you want to happen and how do you want it to happen.

If you want to "redo" some stuff, it sounds like a loop, try to create a function that is "self callable" at it's own end with a way of getting out.

If you create a function, you can call it inside itself.

example:

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

But it would be interesting to add some method of getting out of this loop..

You need to add a loop. Think about what your loop condition is and what needs to be in or outside of the loop. I think something like this is what you are looking for.

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

Since you don't want to reset the players and lives variable you can declare it outside the function as a global variable.Every function will then have the same copy of the variable and therefore you will not reset it. For more reference you can have a look here: https://www.w3schools.com/python/gloss_python_global_variables.asp to understand more about global variables. As Ngeorg mentions you need to have a loop and some kind of condition to rerun the code and stop it at an appropriate time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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