Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.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 在函数中引用全局变量时出现问题_Python_Error Handling - Fatal编程技术网

Python 在函数中引用全局变量时出现问题

Python 在函数中引用全局变量时出现问题,python,error-handling,Python,Error Handling,这是我昨天在这里问到的一个问题的进一步)。我得到一个很好的建议,使用如下函数: getuser = input("Please enter your username :") print("1. render_device") print("2. audit_device") askuser = input("Would you like to render_device or audit_device? : ") def verify_input(sites_set): get

这是我昨天在这里问到的一个问题的进一步)。我得到一个很好的建议,使用如下函数:

getuser = input("Please enter your username :")

print("1. render_device")
print("2. audit_device")

askuser = input("Would you like to render_device or audit_device? : ")

def verify_input(sites_set):

    get_site_name = input("Please enter the site name you'd like to render :")

    if get_site_name in sites_set:
        print('Proceed')
        return
    else:
        print('Not in either list, please enter a valid site')
        verify_input(sites_set)

if askuser == "1":

        sites_2017 = ["bob", "joe", "charlie"]
        sites_2018 = ["sarah", "kelly", "christine"]

        verify_input(set(sites_2017 + sites_2018))
这在函数内部和调用时都能正常工作。但是,问题是我需要
get\u site\u name
作为全局变量,因为它的输入稍后会在脚本中引用(而不是在函数中)。当我将
get\u site\u name
设置为全局时,当输入有效站点时,函数可以引用它并正确工作,但当输入无效站点时,它只会不断循环出现
“不在任何一个列表中”
错误,可能是因为
get\u site\u name
变量中的
raw\u input
未在本地定义

解决这个问题的最佳方法是什么?

关于:

def verify_input(sites_set):

    while get_site_name not in sites_set:
        get_site_name = input("Please enter the site name you'd like to render :")

    print('Proceed')
    return

您的代码使用了
input
函数,但您的问题提到了
raw\u input
,它只存在于Python 2中。您实际使用的是哪个版本的Python?如果您使用的是Python2,那么使用
input
不是一个好主意,您应该使用
raw\u input
。OTOH,如果可以的话,最好使用Python 3。为什么不直接返回变量
get\u site\u name
?我还建议使用while循环,而不是递归调用函数。在问“render\u device或audit\u device”问题之前,应该验证用户。请看一些验证输入的好例子。@PM2Ring很抱歉,我实际上使用的是Python 2,所以它被更新为使用原始输入……这在我粘贴的内容中没有反映出来。