Python Forum

Full Version: Trying to Repeat a Function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I'm quite new to Python and I'm trying to make projects to hone my skills and learn new ones. Currently, I am making a game where your opponent (AI) randomly chooses an action (Attack/Defense) and if they attack, then I want it to choose a random number (Say from 1-10) and store it in a variable. I'm quite confused on how I would go about doing this, mainly how I would repeat a section of the code so when the AI turn is over, it is then the players turn and repeat. I'm also confused on how I would generate a random integer as the other methods I have found online don't seem to work for me. Again, I'm only a beginner and still trying to learn :)
first import random. then use "random.randint(1, 10)" to generate a number 1 - 10. you can repeat in different ways. I'll show you down below

You can use range
for x in range(1, 10):   #Will happen 10 times
    if Variable == 0:   #0 is attack
        num = random.randint(1, 10)
    elif Variable == 1:   #1 is defense
        pass   #Do stuff
You can use while
while defeat == False:
    if Variable == 0:   #0 is attack
        num = random.randint(1, 10)
    elif Variable == 1:   #1 is defense
        pass   #Do stuff
You can have a variable for keeping track of who's turn it is and a function that will trigger another function based on who's turn is is. If it's the player's turn it will trigger this function. If not it will trigger this function. Hope this solves your problem. Also remember to import random
Edit - I just realized you want a function repeated. In that case just execute the function in the lines set to repeat