Search code examples
python-3.xreturn

Value not being returned


being new to this I am probably doing something silly somewhere which is breaking the code. Have taken a look at some similar posts but found nothing that helps.

So, the issue I am having is when I attempt to print newmarbles at the end it is saying it is not defined. I assume I am doing something wrong in terms of returning the value? Thanks in advance for any help.

import random

def playNovice(marbles):
    aimove = random.randint(1, (marbles/2))
    print("AI Move", aimove)
    newmarbles = marbles - aimove
    return newmarbles

def userPlay(marbles):
    usermove = int(input("Enter your move: "))
    while usermove > marbles / 2 or usermove == 0:
        print("Invalid Move")
        usermove = int(input("Enter your move: "))
    else:
        newmarbles = marbles - usermove
        return newmarbles


difficulty = input("Which difficulty? novice or expert: ")
marbles = 100
playNovice(marbles)
userPlay(marbles)
print(newmarbles)

Solution

  • The scope of newmarbles is local to playNovice(). You should assign the returned value to a variable, which may have the same name:

    newmarbles = playNovice(marbles)
    userPlay(marbles)
    print(newmarbles)