在python中使用多个函数的输入变量

问题描述:

我想知道如何在hello()函数的entername()函数中使用'name'变量。在python中使用多个函数的输入变量

这是一个输入变量,是否有人知道如何跨多个函数使用它?

def entername(): 
    name = input("Please enter your name: ") 
    return 

def hello(): 
    text = "Hello " + name + ", welcome to the simulator..." 
    for char in text: 
     sys.stdout.write(char) 
     sys.stdout.flush() 
     char, time.sleep(0.1) 
    print(char) 
    return 

您不能在另一个函数中使用函数范围中定义的变量。你可以,但是,返回名称值,并将其作为参数传递到下一个功能:

import sys, time 

def entername(): 
    name = input("Please enter your name: ") 
    return name 

def hello(name): 
    text = "Hello " + name + ", welcome to the simulator..." 
    for char in text: 
     sys.stdout.write(char) 
     sys.stdout.flush() 
     char, time.sleep(0.1) 
    print(char) 

hello(entername()) # <- this chains the function calls 
        # and is equivalent to 
        # name = entername() # not the same 'name' variable as inside the entername() function, these are different scopes 
        # hello(name) 

另一种选择是使用global变量,但你宁愿避免这种反模式。

+0

非常感谢你! –

+0

很高兴我能帮忙,请看这里:https://*.com/help/someone-answers –

如果要使用来自不同函数的相同“名称”变量,则必须在全局中定义。 在这里,我们在全局范围内定义我们的变量并强制使用全局变量,而不是定义它们自己的局部变量。

import sys, time 

name='' 

def entername(): 
    global name 
    name = input("Please enter your name: ") 
    return 

def hello(): 
    global name 
    text = "Hello " + name + ", welcome to the simulator..." 
    for char in text: 
     sys.stdout.write(char) 
     sys.stdout.flush() 
     char, time.sleep(0.1) 
    print(char) 
    return 

entername() 
hello() 
+0

感谢您的帮助! –

def entername(): 
    name = input("Please enter your name: ") 
    return name 

name = entername()