Search code examples
pythonfunctionloopsfor-loopcoin-flipping

Coin Flip Game function


I am trying to create a function in python where a player starts with a certain amount and then given a certain stake and number of flips it will give the ending amount after the flips

I am a beginner at python and am still getting used to using loops

so what i have is:

import random
def coin(stake, bank, flips):
    for i in range(0,flips):
       H_T = random.randint(0,1) # heads =1  or tails=0
       if H_T ==1:
          k = stake
       else:
          k = -1*stake
       bank = bank + k

I want the function to run so that if for example, there is a win the bank will go up and this will be the new bank then another win or loss will add or subtract from the new bank

i know my loop is wrong but not sure how to fix it


Solution

  • Depending on how you are calling the function, and where you are printing out the result of the coin() function, you may only need to add a return bank statement:

    def coin(stake, bank, flips):
        for i in range(0,flips):
            H_T = random.randint(0,1) # heads =1  or tails=0
            ...
            bank = bank + k
        return bank
    

    sample run:

    >>> print(coin(5, 100, 2))
    90