sirius_pain
sirius_pain

Reputation: 34

Python: Changing a pre-defined variable inside if a function

I'm working on a code for a 'casino' in Python (no GUI yet, just trying to get the codes down for now). I want coins to be a system of currency, and I have a perfectly fine Russian Roulette code. If the player survives, I want the code to add onto the player's coins. Said coins are already defined at the top of the code, outside of the function. When I try

return coins += 100

at the elif clause for the player's survival, I immediately get "invalid syntax" in IDLE. How can I have the function modify 'coins'?

Upvotes: 0

Views: 92

Answers (3)

dawg
dawg

Reputation: 103774

Use coins as a function parameter then return that value with the addition:

coins=2

def f(coins):
    return coins+100

>>> f(coins)  
102

Or just assign coins the value returned:

>>> coins=f(coins)
>>> coins
102
>>> coins=f(coins)
>>> coins
202

Upvotes: 0

arshajii
arshajii

Reputation: 129497

Make sure that you're using coins as a global variable:

>>> coins = 0
>>> 
>>> def f():
...     global coins  # <--
...     coins += 100  # notice also that we're not returning anything
... 
>>> f()
>>> 
>>> coins
100

Upvotes: 2

Hans
Hans

Reputation: 2492

Try return 100 And the caller code would be like coins += russianRoulette() That should work

Upvotes: 0

Related Questions