Skip to content Skip to sidebar Skip to footer

Get User Input And Loop Through A Lot Of Variables In Order To Match That Input To One Of The Variables

I have created an ASCII map of an island in a school project. There are over 140 variables which are used to print the names of the places in the island. I don't just put the names

Solution 1:

READER BEWARE: The OP has had artificial constraints placed on them by their instructor. The mechanism demonstrated here is not something I'd suggest be used in production code. There are better ways of getting similar functionality, namely using common Python data structures rather than individual global variables. The big downside of this method, in addition to it being a hack, is that even though setting the variable values can be done simply by an entered name, you would have to change the code to add new "places". In production code, your map and the individual places on it should be fed to the code as input data. Your code shouldn't have to change when your map or list of places changes.

Knowing just what you want, I took a look, and immediately found that there is indeed a way to set the value of a global variable given its name. That mechanism is the globals() call. This call returns a dictionary containing references to all the global variables. The keys are the variable names, and the values are tied to the actual values of the variables.

Here is the most basic example of this given the code in the question:

x = "x"
y = "y"
red = "\033[31m"# color code

place = input("Where do you want to go?: ")

g = globals()
g[place] = red + g[place]

print("x =", x)
print("y =", y)

Test run 1:

enter image description here

Test run 2:

enter image description here

Notice that the added color code makes the output red from the point where that variable's value is printed until the end of the input.

Here's a more complete example that uses both a color code and an "end color" code so that only the variable's printed value is colored red. In this example, you can keep inputting 1 of w, x, y or z, and then just press Return by itself to exit:

w = "w"
x = "x"
y = "y"
z = "z"

red = "\033[31m"# color code
end="\033[0m"# cancel color code

g = globals()

whileTrue:
    print("w =", w)
    print("x =", x)
    print("y =", y)
    print("z =", z)

    map = x + """ ------------- """ + y
    print("map =", map)

    place = input("Where do you want to go?: ")
    ifnot place:
        break
    g[place] = red + g[place] + end

Test run:

enter image description here

Note here that each variable name that you enter leads to that variable's value being changed to display in red. This occurs because the value of the actual global variable is being modified and then the value of that variable is printed directly. This was the key bit of functionality you were asking for.

BEWARE: This mechanism is not something I'd suggest that you use in production code. There are better ways to do these things, namely using dictionaries or lists. A downside of this method is that even though setting the variable values can be done simply, you still have to change your code to add "places". In production code, your map and the individual places on it should be fed to the code as input data. Your code shouldn't have to change when your map or list of places changes.

I hope this gives you what you needed. Happy programming!

Solution 2:

If I understand correctly, you may have tried using a for loop in the past using a list variable?

Fortunately dictionaries act pretty much the same as lists, only they don't use index:value referencing (i.e. list[index] = value). They use key:value pairing (dict[key] = value).

The syntax uses curly braces like so: dictionary{"key1": value1, "key2": value2, ....}.

This gives you a quick and easy way to reference a value without having to loop through loads of items. Unfortunately, it sounds like you'll have to build the dictionary yourself.

Solution 3:

I think I've got it. So I use a dictionary as mentioned above. I locate the variable containing the string that matches the usr_input, I store its value in a different variable lets call it "random". I remove the matching variable from the dictionary and then I add to the dictionary a new variable with the same name but with the correct value. So code looks something like that:

var1 = "one"
var2 = "two"
red="\033[31m"

dict = {var1: "one", var2:"two"}
print(dict)

Output:

{var1: "one", var2:"two"}

And now we edit that dict:

place = input("Enter: ")
#this is just the usr_input. Its here only so no one asks what does the variable "place" contain.for k,v inlist(dict.items()):
    if v == place:
        random = red + v #random now has the correct value we want
        new_key = f'{k}'#this gets the name of the variable which matches the usr_inputdeldict[k] #deletes the matching variabledict[new_key] = random 
# adds a new variable with the same name as the matching one and the correct value # we got from randomprint(dict)

Output:

{var1: "one", var2:"\033[31mtwo"}

And now comes the part which I don't really now if it satisfies the restrictions. I no longer use the variables as:

map = "------" + var1 + "-------"

I get the values from the dictionary:

map = "-----" + dict[var2] + "-----"

Which gives the correct output. So I am NOT going to abandon nor change this somehow. I will leave it like that and pray there is nothing wrong with it. Completely unorthodox way of doing things but I ended up learning some stuff about dictionaries which I knew nothing about. Only question I got (probably gonna ask in class about it) is: I don't really understand what does the list() do? I only know that without it I get a runtime error.

Other than that, thank you all for the answers and for setting me to the right direction. I know my terminology is so wrong cause I talk about a lot of things I don't fully understand yet. (especially the parts where I say value,variable,key etc) I really think I've messed those up! Hope I wasn't too much of a pain in the back for ya :)

Post a Comment for "Get User Input And Loop Through A Lot Of Variables In Order To Match That Input To One Of The Variables"