是/否输入循环,正确循环问题

2024-05-15 00:00:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编一个简短的猜谜游戏。但是,我不知道如何防止不正确的输入(是/否),阻止用户前进。这是一个工作代码。虽然是真的,但它只会使输入更加混乱。最远的是,它通知玩家,但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来计数。你知道吗

但是如果他们输入了错误的单词(不是“否”也不是“是”),输入的问题就会重复,并再次询问他们(直到他们输入了有效的答案)。在那之后,他们得到了同样的问题,他们没有有效地回答。你知道吗


Tags: noinforreplypointsyestotalprint
2条回答

你需要一个'while'在这里的某个地方,一旦你击中'for'块的末尾,它将转到范围内的下一个值。你知道吗

for y in xrange(len(testQ)):
    bGoodInput = False
    while not bGoodInput:
       reply = str(raw_input('\n'+str(abs(y-5))+ ' - ' +  testQ[y]+' (y/n)  > ')).lower().strip()
       if reply in yes:
           ...
           bGoodInput = True

       elif reply in no:
           ...
           bGoodInput = True

       else:
           ...

while True:将起作用,您需要在满足条件后break退出循环。你知道吗

while True:
    reply = str(raw_input('\n' + str(abs(y - 5)) + ' - ' + testQ[y] + ' (y/n)  > ')).lower().strip()
    if reply in yes or reply in no:
            break

根据更新的作用域,尝试以下操作,似乎break可能导致了您的问题:

reply = False
while reply not in yes and reply not in no:
    reply = str(raw_input('\n' + str(abs(y - 5)) + ' - ' + testQ[y] + ' (y/n)  > ')).lower().strip()

相关问题 更多 >

    热门问题