1

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

Kingsley
  • 12,320
  • 5
  • 24
  • 44
Rito Lowe
  • 23
  • 2
  • What exactly is the problem / your question? "My loop is wrong" isn't a very good problem statement. Please show your expected output and your actual output. – Jonathon Reinhart Dec 13 '18 at 01:54
  • You just need to return bank at the end of your function. It seems to be working OK. Except if this is a gambling simulation, there's no reward for winning, surely it would be something like `k = 2 * stake`! – Kingsley Dec 13 '18 at 01:56
  • Depending on how you are calling the function, you may only need to add a `return bank` statement – davedwards Dec 13 '18 at 01:56

2 Answers2

1

You need to return the bank variable from the function if you want to retrieve it outside of it.

This concept is called variable scope. In Python, a simple function has variables within it which are not recognised outside of it. Google variable scope (or see comment below) for more info.

The for loop seems fine. You add or subtract a stake over a certain number of flips.

Just use return bank at the end (outside the loop).

AER
  • 1,418
  • 18
  • 33
1

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
davedwards
  • 7,011
  • 2
  • 15
  • 45
  • good catch, interesting I didn't pay close attention that the bank was getting updated for each `flip` thanks @Kingsley – davedwards Dec 13 '18 at 02:02