2

I just started with python and I am currently making a snakes and ladders game. Here is my code:

    nameList = []
    def players_name():
        x = 0
        input ("""-Press enter to start inputting players' name.
-Press enter after each name inputed to confirm the name to players list.
-After last name inputed, press enter again without any input to finish.""")
        name = input ("Input players' name:")
        while name != "" or len (nameList) <= 1:
            x = x + 1
            if name in nameList:
                print (name,"is already in list, please input a different name.")
                name = input ("")
            elif name =="" and len (nameList) <= 1:
                print ("A minimum of 2 players are require to start the game.")
                name = input ("")
            else:
                nameList.append(name)
                exec("{} = {}".format(name, "1"))
                numList.append("{0}".format (x))
                name = input ("")
        nameList.sort()
        numList.sort()
        print ("There are",len (nameList),"players inputed in your players list!")
        print ("Your players list:",nameList,"\n")

This is what I got:

    >>> players_name()
    -Press enter to start inputting players' name.
    -Press enter after each name inputed to confirm the name to players list.
    -After last name inputed, press enter again without any input to finish.
    Input players' name:Alvin
    James
    George

    There are 3 players inputed in your players list!
    Your players list: ['Alvin', 'George', 'James'] 
    >>> print(Alvin)
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        print(Alvin)
    NameError: name 'Alvin' is not defined
    >>> 

I am trying to work out why didn't it declare "Alvin" as a variable or why can't i print it out. I am not sure if I am making a silly mistake.

6
  • just to point out that if you sort numList and nameList they will not keep their relation, as they don't sort on the same values. Commented Jan 28, 2014 at 21:24
  • Why would you expect your code to declare Alvin as a variable? I don't see any Alvin = in your code. Commented Jan 28, 2014 at 21:25
  • 6
    I see what you're trying to do. Please don't do it! Your internal variable names should never be based on user input. Commented Jan 28, 2014 at 21:26
  • 1
    Why the downvotes? He/She just probably started learning how to program. How encouraging. Commented Jan 28, 2014 at 21:31
  • I second Mark Ransom's advice. See also: Keep data out of your variable names Commented Jan 28, 2014 at 21:34

4 Answers 4

5

Keep your data out of your variable names; don't use exec here, store your players in dictionary instead!

players = {}

name = input ("Input players' name:")
while name len(players) < 2:
    x = x + 1

    if name in players:
        print (name,"is already in list, please input a different name.")
        name = input ("")
    elif not name and len(players) < 2:
        print ("A minimum of 2 players are require to start the game.")
        name = input ("")
    else:
        players[name] = 1
        numList.append(str(x))
        name = input ("")

nameList = sorted(players.keys())
print ("There are {} players inputed in your players list!".format(len(nameList)))
print ("Your players list:", nameList)

Your code only assigns 1 to each name; I've replicated that here by assigning 1 as the value in the dictionary for each player name. You can store other things per player name too, including instances of your own custom classes.

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

Comments

1

This is wrong, you shouldn't do that. But if you have your reasons...

Instead of execing, modify locals() (vor local scope variables) or globals() (for global scope variables).

For example:

locals()["a"] = 5
globals()[<value from user>] = 1

1 Comment

Modifying the dictionary returned by locals is not guaranteed to affect the values of local variables.
0

Alvin is an element of your list which looks like this:

 nameList = [`Alvin`, `George` ...]

You should access elements of the list like this:

 print nameList[0]

Comments

0

Basically, you have a list of strings (string is a pice of text). String 'Alvin' is not a variable Alvin. Those are two different things. If you want a variable you need to declare one

alvin = "Alvin"

and then you can print it with print alvin, but let's back up what is your problem. List is a collection that you can access by index e.g nameList[0]. Martijn Pieters advice is great, but if you don't know what a dictionary is list is good enough for now.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.