for vs.if循环*错误选择*

2024-04-26 06:11:14 发布

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

试着做一个填空测验。你知道吗

如果我在答案不正确时使用for循环,它将始终返回到列表中的第一个元素,有什么方法可以绕过它吗?或者使用不同的循环?你知道吗

请参阅下面的完整代码。 这不是最终决定 只适用于简单的答案选择。 当正确回答第一个空格(想象)和第二个空格失败时,问题就会出现。你知道吗

任何帮助都将受到高度赞赏。你知道吗

imag = '***1*** there is no heaven, It is ***2*** if you try, No hell below us, Above us only sky, ***1*** all the people living for today, ***1*** there is no ***3***, It is not hard to do, Nothing to kill or die for, And no religion too, ***1*** all the people living life in ***4***.'
imag_ans = ['Imagine', 'easy', 'heaven', 'peace']
blanks = ['***1***', '***2***', '***3***', '***4**']    

def level():
    print 'Please select Level? (Easy / Medium / Hard)'
    global a
    a = raw_input()
    if a == 'Easy':
        return attempts()
    if a == 'Medium':
        return 'Med'
    if a == 'Hard':
        return 'Hard'
    else :
        print 'Invalid option'
        print '\n'
        return level()

def attempts():
    print 'How many attempts will you need?'
    global numberofatt
    numberofatt = raw_input()
    try:
        float(numberofatt)
    except ValueError:
        print "Please enter a number for attempts"
        return attempts()
    numberofatt = int(numberofatt)
    if numberofatt <= 0 :
        print 'Please enter a positive number'
        return attempts()
    else :
        return quiz(a)

def quiz(level):
    i = 0
    global user_ans
    global i
    print 'Please fill in the blanks, you have ' + str(numberofatt) + ' attempts'
    for blank in blanks:
        print 'Fill in blank' + blank 
        user_ans = raw_input()
        if user_ans == imag_ans[i]:
            i = i + 1
            global imag
            imag = imag.replace(blank, user_ans)
            print "Correct!"
            print imag  
        else :
            return att()

n = 1
def att():
    if n == numberofatt :
            return 'Game Finished'
    if user_ans != imag_ans[i]:
        global n
        n = n + 1
        #blank = 0
        print 'Try Again'
        return quiz(a)


print level()

Tags: inforreturnifisdeflevelglobal
1条回答
网友
1楼 · 发布于 2024-04-26 06:11:14

可以使用while循环:

def level():
    global a
    a = raw_input('Please select Level? (Easy / Medium / Hard): ')
    pending = True
    while pending:
        if a == 'Easy':
            pending = False
            return attempts()
        elif a == 'Medium':
            pending = False
            return 'Med'
        elif a == 'Hard':
            pending = False
            return 'Hard'
        else :
            print 'Invalid option'
            print '\n'

类似的东西可以应用于quiz()。如前所述,您应该检查global是如何工作的。另外,修改缩进(例如:in att())。你知道吗

相关问题 更多 >