简体   繁体   中英

Issue with referencing a global variable within a function

This is further to an issue I asked about on here yesterday What is the best way to validate user input against the contents of a list? ). I got a good suggestion using a function like so:

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))

This works correctly within the function and when it is called. However, the issue is that I need get_site_name as a global variable since its input is referenced later in the script (not in a function). When I make get_site_name global, the function can reference it and works correctly when a valid site is input, but when an invalid site is input it just keeps looping the "Not in either list" error over and over, probably because the raw_input in the get_site_name variable isn't defined locally.

What would be the best way to remedy this?

What about:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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