Home > Blockchain >  I've defined my variable at the beginning, but whenever I use the variable, it says it's n
I've defined my variable at the beginning, but whenever I use the variable, it says it's n

Time:01-14

I'm fairly new at python, haven't used it in a while, but I've written a betting script, with a declared variable at the beginning called 'cash' but whenever I call it later in the script, it says its undefined. the specific error is

  File "main.py", line 11, in <module>
    cash  = bettingAmount
NameError: name 'cash' is not defined

and my code is

cash: 500
import random
print ("Betting Simulator")

bettingAmount = input("type the ammount your going to bet")

if random.randrange(1,2) == 2 :
    cash -= bettingAmount 
    print(cash)
else:
    cash  = bettingAmount
    print(cash)

my question is most likely very silly, but a have no idea what the problem is. im pretty new to python.

CodePudding user response:

Welcome to python!

Correct, you do define cash, but hidden in the -= operator, you actually reference cash right before you define it.

cash -= bettingAmount expands into cash = cash - bettingAmount

You can't subtract bettingAmount from cash before cash is first assigned!

so initialize cash to something, say cash=100 before your if statement.

CodePudding user response:

It is simply the fact that you are using : instead of = to assign a value. Using a colon is not equivalent to using an equals sign in python.

Hope this helps!

  • Related