【发布时间】:2016-02-21 06:03:18
【问题描述】:
如果按下回车键,我需要让我的程序在 Python 中重新开始。我找到了这个问题和解决方案:how to check if the enter key is pressed python。然而,当我用谷歌搜索 event.keysym 时,它似乎与 Tkinter 有关,我认为我没有。
当我尝试使用该解决方案时出现错误:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if event.keysym == 'Return':
NameError: name 'event' is not defined
我是一个新手,刚刚完成了 Coursera 上 Severance 博士的课程。
这是我写的在工作中扮演猪和牛的程序。一切都按我的意愿工作。唯一的问题是,如果按下“enter”按钮以外的任何键,则退出程序。
while True:
while True:
word= raw_input("Enter a four letter English word with no repeating letters: ")
print
if len(word) <> 4:
print "What part of 'four letter word' did you not understand? Try again."
print
continue
else: break
guesses = 0
while True:
correct = 0
position = 0
cnt = 0
result = 0
guess= raw_input("Enter a guess: ")
guesses = guesses+1
#print "guessses", guesses
for w in guess:
cnt = cnt+1
#print "cnt", cnt
position=0
for g in word:
position=position+1
#print "position", position
if g == w:
correct = correct+1
if position == cnt:
result = result+1
#print "result", result
print
print "Number correct:", correct
print "Number in the right position:", result
print
if correct<>4 and result<>4:
print "Give me another guess"
print
continue
elif correct == 4 and result == 4:
print
print "YOU WIN"
print
print "It took you", guesses, " guesses to get it right"
print
break
answer= raw_input("press ""enter"" to play again")
if event.keysym == 'Return':
continue
else:
exit
print
print
然后我想,也许我已经用我的字符串变量“answer”替换了“event”,但后来我得到了这个错误:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if answer.keysym == 'Return':
AttributeError: 'str' object has no attribute 'keysym'
另外,如果我按下任何其他键,它只会在 Idle 中打印并且程序不会退出。
顺便说一句,我知道必须有更好的方法来使用列表或字典进行编程,但我只知道该怎么做。
【问题讨论】:
标签: python python-2.7