I am practicing in Python and I decided to create a simple roulette simulation with colors only for now. However, I also wanted to make it possible to bet on color. But it seems like I did something wrong, since for some reason I can't use the global variable 'balance' in one of the function. Also, I didn't come up with the idea of how to make bet a global variable. I tried to take it out so that it become the global variable with input function, however in this case it has the same issue as with balance variable.
import random
balance = 100
# user decides how much they will bet
def start():
print("Place your bet:")
bet = int(input(">"))
if bet > balance:
insufficient_funds()
else:
simulate()
# if user placed too much
def insufficient_funds():
print("Oops, your don't have enough funds to place a bet")
start()
# color choose and roulette simulation
def simulate():
print("Choose Red or for Black:")
answer = input("> ")
result = random.randint(1, 2)
if result == 1 and answer == "Red":
print("You won")
balance += bet
print(f"Your balance now {balance}")
start()
elif result == 2 and answer == "Black":
print("You won")
balance += bet
print(f"Your balance now {balance}")
start()
else:
print("You lost!")
balance -= bet
print(f"Your balance now {balance}")
start()
start()
I know it is super basic, but for now I try to make it as simple as possible to practice with python's fundamental things w/o using a lot of modules. I'd extremely appreciate if you could help me out with it.
Your code is awesome. The way python works, you have to explicitly tell it that you're going to use a global variable by using the global
keyword. If you don't, it will create a new local variable within the function. Try:
import random
balance = 100
# user decides how much they will bet
def start():
global balance
print("Place your bet: ")
bet = int(input(">"))
if bet > balance:
insufficient_funds()
else:
simulate(bet)
# if user placed too much
def insufficient_funds():
print("Oops, your don't have enough funds to place a bet")
start()
# color choose and roulette simulation
def simulate(bet_amount):
global balance
print("Choose Red or for Black:")
answer = input("> ")
result = random.randint(1, 2)
if result == 1 and answer == "Red":
print("You won")
balance += bet_amount
print(f"Your balance now {balance}")
start()
elif result == 2 and answer == "Black":
print("You won")
balance += bet_amount
print(f"Your balance now {balance}")
start()
else:
print("You lost!")
balance -= bet_amount
print(f"Your balance now {balance}")
start()
start()
This is how you let Python know you're calling a global variable. To avoid variable shadowing, we can use bet
in the start
function, and then when we call it in the simulate
function, we'll tell it that we need a bet_amount
.