[英]Python NameError: name is not defined for my script
我有一個python腳本,並且收到以下錯誤。 我是該語言的新手,因此我創建了一個簡單的腳本,稱為Writing.py,以將參與者的姓名和分數寫入名為scores.txt的文本文件中。 但我不斷收到此錯誤:
Traceback (most recent call last):
File "writing.py", line 4, in <module>
participant = input("Participant name > ")
File "<string>", line 1, in <module>
NameError: name 'Helen' is not defined
這是我的代碼:
f = open("scores.txt", "w")
while True:
participant = input("Participant name > ")
if participant == "quit":
print("Quitting...")
break
score = input("Score for " + participant + "> ")
f.write(participant + "," + score + "\n")
f.close()
我猜您正在使用Python 2.x
,在Python 2.x中, input
實際上會在返回結果之前嘗試評估輸入,因此,如果您輸入一些名稱,它將把它視為變量並嘗試獲取其值。引起問題。
使用raw_input()
。 代替。 范例-
participant = raw_input("Participant name > ")
....
score = raw_input("Score for " + participant + "> ")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.