我正在努力开发一个课程作业的解决方案,我的学生必须完成这项任务,并且我坚持在函数之间传递变量。我在一个生成以下数据的函数中创建了一个测验:
我需要将这些数据传递给第二个函数,然后将该数据附加到文件中(取决于学生所在的组)。
我的代码看起来像这样,因为我试图将数据作为字符串/列表作为参数传递给第二个函数:
def Quiz():
#Code to collect user details and generate scoe (10 random questions)
strSave=input("Do you want to save your score? y/n")
if strSave.lower()=="y":
result=(strFirstName+","+strLastName+","+str(score))
#Stores the required data as a csv string
return result
#?passes the data back?
funcSave()
elif strSave.lower()=="n":
funcQuiz()
#restarts the quiz function
def funcSave(result):
#The function to save the score(s) to file
group=input("Which group are you A1, A2 or A3?\n")
if group=="A1":
file=open("A1.txt","a")
file.write(result)
#error is that result is not defined
file.close()
elif group=="A2":
file=open("A2.txt","a")
file.write(strFirstName+","+strLastName+","+str(score))
file.close()
elif group=="A3":
file=open("A3.txt","a")
file.write(strFirstName+","+strLastName+","+str(score))
file.close()
else:
print("unknown")
答案 0 :(得分:2)
你的问题在这里:
return result #immediately ends the method, returning result to the caller
funcSave() # Is never executed because you've return'd. Would throw TypeError if it did because funcSave() needs one argument
您需要移除return
来电,然后实际传递results
方法中的Quiz
变量,如下所示:
funcSave(results)
您在Quiz
中也有一个拼写错误,它会调用funcQuiz()
而不是Quiz()
来重新启动。
顺便说一句,而不是:
result=(strFirstName+","+strLastName+","+str(score))
你可以这样做:
result = ','.join((strFirstName,strLastName,str(score)))
python中的join
方法使用.
之前的字符串作为分隔符将值列表连接在一起。它比使用+
更有效,因为python不需要创建任何中间字符串。请注意,join
期望所有值都是字符串,因此您仍然需要score
上的强制转换。
答案 1 :(得分:0)
而不是
return result
#?passes the data back?
funcSave()
DO
funcSave(result)
另外,将Quiz
功能重命名为funcQuiz
,以便重新启动。
答案 2 :(得分:0)
我认为您在将数据传递给funcSave函数之前返回数据。如果要将数据传递给另一个函数中的函数,则不希望返回数据。返回数据允许您从函数中获取数据,但它也会结束函数的执行。
试试这个:
def Quiz():
#Code to collect user details and generate scoe (10 random questions)
strSave=input("Do you want to save your score? y/n")
if strSave.lower()=="y":
result=(strFirstName+","+strLastName+","+str(score))
# Pass the result to the funcSave function instead of returning it.
funcSave(result)
elif strSave.lower()=="n":
# rename the funcQuiz() function to Quiz() so it is called correctly
Quiz()
#restarts the quiz function
def funcSave(result):
#The function to save the score(s) to file
group=input("Which group are you A1, A2 or A3?\n")
if group=="A1":
file=open("A1.txt","a")
file.write(result)
#error is that result is not defined
file.close()
elif group=="A2":
file=open("A2.txt","a")
file.write(strFirstName+","+strLastName+","+str(score))
file.close()
elif group=="A3":
file=open("A3.txt","a")
file.write(strFirstName+","+strLastName+","+str(score))
file.close()
else:
print("unknown")