Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 从用户定义函数调用变量_Python 3.x - Fatal编程技术网

Python 3.x 从用户定义函数调用变量

Python 3.x 从用户定义函数调用变量,python-3.x,Python 3.x,代码可能有缺陷,我只是用它来说明我的观点,但请随意指出我需要知道如何调用在用户定义函数中定义为输入的变量的任何错误。目前我的错误是没有定义全局名称'name' import time def createIdentity(): print ("Please Enter your details below") time.sleep(1) name = input("What is your name?") time.sleep(1) age = inpu

代码可能有缺陷,我只是用它来说明我的观点,但请随意指出我需要知道如何调用在用户定义函数中定义为输入的变量的任何错误。目前我的错误是没有定义全局名称'name'

import time

def createIdentity():
    print ("Please Enter your details below")
    time.sleep(1)
    name = input("What is your name?")
    time.sleep(1)
    age = input("How old are you?")
    time.sleep(1)
    gender = input("Are you male or female?")

def recallIdentity():
    print("Your name is " + str(name) + "you are " + str(age) + "And you are a " +     str(gender) + "!")


createIdentity()
recallIdentity()

您需要返回在createIdentity中输入的值,然后将返回的值传递给RecAllidity。一个函数中定义的变量名与另一个函数中具有相同名称的变量不同

我会用字典,所以:

import time

def createIdentity():
    user = dict()
    print ("Please Enter your details below")
    time.sleep(1)
    user['name'] = input("What is your name?")
    time.sleep(1)
    user['age'] = input("How old are you?")
    time.sleep(1)
    user['gender'] = input("Are you male or female?")
    return user

def recallIdentity(user_out):
    print("Your name is " + user_out['name'] + "you are " + user_out['age'] + "And you are a " + user_out['gender'] + "!")

user_dict = createIdentity()
recallIdentity(user_dict)

默认情况下,函数是完全自包含的。你要么计算你的变量,要么把它们作为参数传入,要么从其他函数返回它们——另一种计算形式

然而,也有全局变量之类的东西。使用全局变量,您可以在一个函数中设置它们,在另一个函数中访问它们,值将继续

在python中,必须告诉python变量在每个函数中都是全局的,在每个函数中都使用它作为全局变量

例如:

def f():
  x = 1    # NOT global

def g():
  global x
  x = 1    # Global x.

def h():
  print("X is %d" % x)   # NOT a global x

def i():
  global x
  print("X is %d" % x)    # Global x.

在您的示例中,我相信您需要全局行为—g和I函数。

非常感谢,如果不太麻烦的话,出于好奇,我肯定会使用它。除了库之外,您还会使用其他库吗?库?你是说字典吗?如果是这样,您还可以执行返回名称、年龄、性别之类的操作,然后使用a、b、c=createIdentity捕获返回值。然后你可以将部分或全部传递给另一个函数。再次感谢,是的,对不起,我一直在忙着制作我自己的库以从中导入,所以这就是我混淆的地方。谢谢你,使用字典要简单得多,虽然我想我会研究字典,只是为了扩展我的vocabPlease,如果可能的话,尽量避免全球冲突。这是过去所谓的软件危机的原因之一。您想要创建类的对象。实际上,这是一个适合类、实例变量和方法的好例子。对于最简单的类别来说,你想要实现的事情是自然的。您希望将数据和方法放在一起。