对此我不熟悉我可能正在做一些愚蠢的事情,这会破坏代码。看了一些类似的帖子但发现没有任何帮助。
所以,我遇到的问题是当我试图在最后打印新品时它说它没有定义。我假设我在返回值方面做错了什么?在此先感谢您的帮助。
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)
答案 0 :(得分:1)
返回语句不返回变量,它们返回一个值。
playNovice(marbles)
将返回newmarbles
的值,然后对其执行任何操作,您想要的是执行类似
int aVariable = playNovice(marbles);
print(aVariable);
这会将方法playNovice
的返回值分配给变量aVariable
。
答案 1 :(得分:1)
newmarbles
的范围是playNovice()
的本地范围。您应该将返回的值分配给变量,该变量可能具有相同的名称:
newmarbles = playNovice(marbles)
userPlay(marbles)
print(newmarbles)