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.

  • 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. – njzk2 Jan 28 '14 at 21:24
  • Why would you expect your code to declare `Alvin` as a variable? I don't see any `Alvin =` in your code. – kindall Jan 28 '14 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. – Mark Ransom Jan 28 '14 at 21:26
  • 1
    Why the downvotes? He/She just probably started learning how to program. How encouraging. – Lukasz Madon Jan 28 '14 at 21:31
  • I second Mark Ransom's advice. See also: [Keep data out of your variable names](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) –  Jan 28 '14 at 21:34
  • See [_Why you don't want to dynamically create variables_](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html). – martineau Jan 28 '14 at 22:11

4 Answers4

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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
Filip Malczak
  • 3,124
  • 24
  • 44
  • Modifying the dictionary returned by `locals` is not guaranteed to affect the values of local variables. – chepner Jan 28 '14 at 21:37
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]
oz123
  • 27,559
  • 27
  • 125
  • 187
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.

Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108