4

Running the following

golfFile = open("golf.dat","a")
another = "Y"
while another=="Y":
    Name = input("What is the player's name?: ")
    Score = input("What is the player's score?: ")
    golfFile.write(Name+"\n")
    golfFile.write(Score+"\n")
    another = input("Do you wish to enter another player? (Y for yes): ")
    print()
golfFile.close()
print("Data saved to golf.dat")

Getting the following error What is the player's name?: j

Traceback (most recent call last):
  File "C:\Users\Nancy\Desktop\Calhoun\CIS\Chapter10#6A.py", line 4, in <module>
    Name = input("What is the player's name?: ")
  File "<string>", line 1, in <module>
NameError: name 'j' is not defined

2 Answers2

2

In Python 2.7, input tries to evaluate the input as a Python expression, while raw_input evaluates it as a string. Obviously, j is not a valid expression. Using input is in fact dangerous in some cases -- you don't want users to be able to execute arbitrary code in your application!

Thus, what you're looking for is raw_input.

Python 3 doesn't have raw_input, and the old raw_input has been renamed input. So, if you tried your code in Python 3, it would work.

golfFile = open("golf.dat","a")
another = "Y"
while another=="Y":
    Name = raw_input("What is the player's name?: ")
    Score = raw_input("What is the player's score?: ")
    golfFile.write(Name+"\n")
    golfFile.write(Score+"\n")
    another = raw_input("Do you wish to enter another player? (Y for yes): ")
    print()
golfFile.close()
print("Data saved to golf.dat")

Test:

>>> Name = input("What is the player's name?: ")
What is the player's name?: j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'j' is not defined
>>> Name = raw_input("What is the player's name?: ")
What is the player's name?: j
>>> Name
'j'
vroomfondel
  • 3,056
  • 1
  • 21
  • 32
1

You may want to use raw_input instead of input:

Name = raw_input("What is the player's name?: ")
Score = raw_input("What is the player's score?: ")
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73