【发布时间】:2016-10-12 21:15:32
【问题描述】:
我正在编写一个简短的猜谜游戏。但是,我不知道如何防止错误输入(是/否),从而阻止用户继续前进。这是一个工作代码。尝试使用 while True 但它只会使输入更加混乱。最远的是 else 通知玩家,但 q 计数向前移动。
# -*- coding: cp1250 -*-
import sys
def genVprasanja ():
yes = set(['yes','y', ''])
no = set(['no','n'])
testQ = ['hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER', 'hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER2', 'hello1', 'hello33112', 'hello332', 'hello2', 'hello4','hellomore', 'ANSWER3']
points = 5
total = 0
for x in range(0,3):
for y in xrange(len(testQ)):
reply = str(raw_input('\n'+str(abs(y-5))+ ' - ' + testQ[y]+' (y/n) --> ')).lower().strip()
if reply in yes:
print '\ncorect!\n\nAnswer is :',testQ[5], '\n\nPoints: ',points, '\n'
total = total + points
print 'Total: ', total, '\n'
break
elif reply in no:
points = points - 1
if points != 0:
print '\nwrong!', '\n\nNext question for: ',points
else:
print '\nThe end!\n\n' 'Every anwser is wrong!\n\nYou got 0 points.\n\Correct answer is:', testQ[5],'\n\n'
total = total + points
print 'SKUPNE TOČKE: ', total
break
else:
sys.stdout.write("\nPlease press 'RETURN' or 'N'\n")
points = 5
genVprasanja()
编辑:
每位玩家都可以回答三组 5 个问题。他们收到问题,直到他们说是。如果他们说没有 5 次循环结束(3 次) - 我正在使用 var points 来计数。
但是,如果他们输入了错误的单词(不是 no 和 not yes),输入的问题就会重复自己再次询问他们(直到他们输入一个有效的答案)。之后,他们得到了同样的问题,他们未能正确回答。
【问题讨论】:
-
太多的空白...
-
函数体需要缩进。
-
真的很抱歉,我在分解代码,发帖的时候忘记去掉ws了....
-
raw_input()返回一个字符串,不需要使用str()将其转换为字符串。 -
if (reply not in yes) and (reply not in no): continue,其中continue重复循环