0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
mistertim
  • 9
  • 3
  • 2
    Your code uses the `input` function, but your question mentions `raw_input`, which only exists in Python 2. Which version of Python are you actually using? If you _are_ using Python 2, it's _not_ a good idea to use `input`, you should use `raw_input` instead. OTOH, it's much better to use Python 3, if you can. – PM 2Ring Aug 22 '18 at 15:49
  • 3
    Why not just return your variable `get_site_name`? I would also suggest using a while loop instead of recursively calling your function. – busybear Aug 22 '18 at 15:49
  • You should validate the user before you ask the "render_device or audit_device" question. Please take a look [here](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) for some good examples of validating input. – PM 2Ring Aug 22 '18 at 16:01
  • @PM2Ring sorry about that, I actually am using Python 2, so it was updated to use raw_input...that just wasn't reflected in what I pasted in. – mistertim Aug 22 '18 at 16:42

1 Answers1

0

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
Drachenfels
  • 3,037
  • 2
  • 32
  • 47