繁体   English   中英

Def函数python:raw_input不存储

[英]Def function python: raw_input not store

我是python的新手。 自从2013年开始在大学学习以来,我一直在努力学习如何很好地了解python。 对不起,如果有点混乱。

让我在下面显示我的问题。 我有一些def函数看起来像:

def thread_1():
                a = input('Value UTS (100) = ')
                if a > 100:
                    print line2
                    d=raw_input('Dont higher than 100. Input y to repeat : ') 
                    d='y'
                    if d=='y' :
                        thread_1()
                    return a

def thread_2():
                b = input('Value UAS (100) = ')
                if b > 100:
                    print line2
                    d=raw_input('Dont higher than 100. Input y to repeat : ') 
                    d='y'
                    if d=='y' :
                        thread_2()
                    return b
def thread_3():                         
                c = input('Value Course (100) = ')
                if c > 100:
                    print line2
                    d=raw_input('Dont higher than 100. Input y to repeat : ') 
                    d='y'
                    if d=='y' :
                        thread_3()
def thread_4():                                                          
                value_total = a*50/100+b*30/100+c*20/100

这是我的表达定义到程序列表中

if p==1:
            thread_1()
            thread_2()
            thread_3()
            thread_4()

最后,我运行此程序:只要输入数字正确,但最后显示如下错误代码的程序:

Traceback (most recent call last):   File "ganjil-genap.py", line 71, in <module>
    thread_4()   File "ganjil-genap.py", line 36, in thread_4
    value_total = a*50/100+b*30/100+c*20/100 NameError: global name 'a' is not defined

谁能让我知道我做错了什么?

提前致谢。

您可能忘记了thread_*函数的参数。

例如, thread_4函数声明需要如下所示:

def thread_4(a, b, c):                                                          
    value_total = a*50/100+b*30/100+c*20/100

另外,您还必须在函数调用中为函数提供参数,例如:

if p==1:
    a=1, b=2, c=3   
    thread_1(a, b, c)
    thread_2(a, b, c)
    thread_3(a, b, c)
    thread_4(a, b, c)

您仅在这些函数中定义了在线程_1,线程_2和线程_3上使用的变量a,b和c。 “ a”仅在线程_1内定义,在线程_2内定义b,在线程_3内定义c,但它们不是主程序的全局变量。 该声明

return a 

仅返回变量a的值。

您应该将这些商品设置为全球性。 我认为它应该像这样:

a=0
def thread_1():
   global a
   a= raW_input....

这将使您的a,b,c变量成为全局变量。

然后应在thread_4()中将a,b和c作为函数的参数传递。

def thread_4(a,b,c):

我认为这应该有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM