【问题标题】:for vs. if loop *incorrect selection*for vs. if 循环 *不正确的选择*
【发布时间】:2018-03-10 04:12:05
【问题描述】:

尝试创建填空测验。

如果我在答案不正确时使用 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()

【问题讨论】:

  • 没有“if循环”这样的东西
  • 甚至不清楚你在问什么。
  • 您可能还想检查global 的工作原理。

标签: python python-2.7


【解决方案1】:

你可以使用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 的工作方式。另外,修改缩进(例如:att())。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多