gpt4 book ai didi

python - 使用函数返回的变量时出现 NameError

转载 作者:太空宇宙 更新时间:2023-11-04 00:59:31 26 4
gpt4 key购买 nike

我想返回变量aRoll,并将其用作下一个函数的参数。在这种情况下,aRoll 包含“让我们滚动你的能力分数。准备好了吗?(是/否)”问题的答案,一旦问题得到回答,原始输入将存储在变量 中aRoll 并返回。

import random

pAbility = ['Str', 'Dex', 'Con', 'Int', 'Wis', 'Cha']
pScore = []

i = 0

def pQuestion():
aRoll = raw_input("Let's roll your ability scores. ready? (y/n)")
if aRoll not in ('y', 'n'):
print "Please type 'y' or 'n'"
return pQuestion()
else:
return aRoll

def pStats(aRoll):
while aRoll == "y":
while i < 6:
pScore.append(random.randint(7, 18))
i = i + 1

for score, ability in zip(pAbility, pScore):
print str(score) + ":\t\t " + str(ability)

def pReroll():
aRoll = raw_input("Do you wish to reroll? (y/n)")
aRoll = aRoll.lower()
if aRoll not in ('y', 'n'):
print "Please type 'y' or 'n'"
return pReroll()

pQuestion()

pStats()

pReroll()

当在脚本底部的 pQuestion() 之后放置 print aRoll 时,它告诉我 aRoll 未定义。我没有正确返回 aRoll 吗?

最佳答案

aRoll 定义为每个函数中的单独局部变量。您要么需要将其声明为全局函数(这不是一个好主意),要么显式地将一个函数的返回值作为参数传递给下一个函数。例如,

rv = pQuestion()
rv2 = pStats(rv)
rv3 = pReroll(rv2)

(注意这需要在 pReroll 的定义中进行更改。)

关于python - 使用函数返回的变量时出现 NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com