Python2.7/Confused with variables

Question:

initial_p = input("Enter the initial point")

def game():
    x = 1
    guess = input("Guess value")
    if guess == 1:
        initial_p += 2
    else:
        initial_p -= 2

game()

replay = raw_input("Do you want to try it again? Y/N")
if replay == 'Y':
    game()

each game needs 2 points

I made it really simple just to explain this stuff easily

So to play each game, it requires you to have at least 2 points otherwise it becomes game over
if you guess right, you earn 2 points
if not, you lose 2 points.

with the outcome(points), you can either play again or quit

if you play again, you pay two points

HOWEVER, when you play for the second time or more, that line

initial_p += 2 and initial_p -= 2 still have points that you typed in the very beginning

Asked By: SMLJ

||

Answers:

The quick and dirty response is to change to the following.

def game(initial_p):
    #Your Code
    return initial_p


initial_p = game(initial_p)

Basically, you’re placing the global variable as a local variable and reassigning the global.

This should also happen at the very bottom as well.

Also, you can just ask for the input inside of the function, and have a default argument of initial_p.

For example,

def game(first_time=True)
    #Ask for input with if first_time:
    return initial_p

And modify some global point value or something from the return.

Sorry if this is sloppy, was written on my mobile.

Answered By: AdriVelaz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.