for if if loop *错误选择*

时间:2017-09-28 12:08:37

标签: python python-2.7

尝试在空白测验中创建填充。

如果我在答案不正确时使用for循环将始终返回列表中的FIRST元素,有没有办法绕过这个?或使用不同的循环?

请参阅下面的完整代码。 这不是最终的 仅适用于EASY答案选择。 正确回答第一个空白(想象)并在第二个空白时失败时会出现此问题。

任何帮助都会被高度评价。

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()

1 个答案:

答案 0 :(得分:0)

您可以使用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()应用类似的内容。如评论所述,您应该检查全球是如何运作的。另外,修改缩进(例如:att())。