【问题标题】:How can I use a value that is already inside a function in another function?如何在另一个函数中使用已经在函数内部的值?
【发布时间】:2015-05-03 07:56:42
【问题描述】:

我正在开发一个构建测验的程序。 我需要从第一个循环中取出我的“真实”,以便在第二个循环中使用它。

就像现在一样,Python 说"true" is not defined

def verif(): #this is the function to check if answer was right
    y=(chosen_answer.get())
    true=0
    if chosen_answer==1:
       true=true+1
    else:
        true=true  #at the end true represents the number of correct answers
    return true 
def final_count():
    if true==2:   #here it shows that "true" was not identified
        print("All of the answers were answered correctly!")
    elif true==1:
        print("50% were answered correctly")
    else:
        print("none of the answers were right..")

【问题讨论】:

  • 你没有任何循环,你的意思是指veriffinal_count函数?
  • 一般来说,使用像true 这样的语言结构作为变量名是个坏主意。 final_count 是一个完全独立于verif 的函数,因此不能像那样共享变量。
  • 确实,对不起,我指的是功能。有什么办法可以分享吗? @Huey
  • 可以使用全局变量在函数之间共享
  • @Huey true 不是任何版本的 Python 中的语言结构,仅供参考。但是你的观点仍然有效。

标签: python loops if-statement tkinter


【解决方案1】:

传递是作为参数:

def final_count(true):
    if true==2:   
        print("All of the answers were answered correctly!")
    elif true==1:
        print("50% were answered correctly")
    else:
        print("none of the answers were right..")

既然你return它在verif函数中,你可以简单地运行

true = verif()
final_count(true)

我建议将变量名从 true 更改为 count 或其他任何名称。此外,在处理局部变量时,您不必保持相同的名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-30
    • 2019-05-04
    • 2019-09-11
    • 1970-01-01
    • 2017-09-22
    • 2014-07-31
    • 2021-11-20
    • 2017-05-08
    相关资源
    最近更新 更多