0

I'm relatively new to python, and I can't figure out how to do this. I need to take a number input from a user, then turn that into an already existing variable. So far, I've managed to take the input, but I don't think I can make it into a variable. I am trying to turn this said input (number) to be added onto the back of a string (the string is pos)

So, for example, If I entered the number 1, i would have pos1, 2 would be pos2, so on.

if win == 0:
    displayboard()
    newPlot = input("")
    postochange = "pos"+newPlot
    if postochange == "X" or "O":
        print ("Sorry, but that space is taken!")
    else:
        if playerTurn == 1:
            postochange = "X"
        else:
            postochange = "O"

I'll try to simplify this some more, I want to have the user give me a number, that I add to the text "pos" and that corresponds to a variable that I already have.

2
  • What you’re trying to do would be better accomplished by a list or dict. Consult the online documentation. Commented Oct 23, 2019 at 23:02
  • 1
    Are you getting an error? Maybe you just need to cast newPlot to a str? posttochange = "pos"+str(newPlot) Commented Oct 23, 2019 at 23:03

2 Answers 2

1

Can you instead use a dictionary of values e.g.:

pos_s = {'pos1':None,
         'pos2':None}

pos_s['pos'+str(user_number)] = desired_value

then to get the value of the variable you would do this:

pos_s.get('pos'+str(user_number), None)

Sign up to request clarification or add additional context in comments.

2 Comments

make sure the user_number is a string not an int
This works, had to change some other stuff in the script but it works fine. Thanks for the help
0

just complementing Mason Caiby's answer, if the final user can only enter a finite collection of values, I would validate the entry with a set. Then you can associate/correspond to a variable that you already have.


# Python program to demonstrate differences 
# between normal and frozen set 

# Same as {"a", "b","c"} 
normal_set = set(["a", "b","c"]) 

# Adding an element to normal set is fine 
normal_set.add("d") 

print("Normal Set") 
print(normal_set) 

# A frozen set 
frozen_set = frozenset(["e", "f", "g"]) 

print("Frozen Set") 
print(frozen_set) 

# Uncommenting below line would cause error as 
# we are trying to add element to a frozen set 
# frozen_set.add("h") 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.