2

总新手在这里。

那么,如果满足某些条件,有什么方法可以阻止执行功能?

这是我的源代码:

answer = raw_input("2+2 = ")
if answer == "4":
    print "Correct"
else:
    print "Wrong answer, let's try something easier"
    answer = raw_input("1+1 = ")
if answer == "2":
    print "Correct!"
else:
    print "False"

所以基本上,如果我在第一个问题上输入 4,我会从下面的“else”函数中得到“False”评论。如果在第一个问题上输入 4,我想阻止这种情况发生。

4

2 回答 2

3

缩进级别在 Python 中很重要。只需缩进第二个if语句,使其成为第一个语句的一部分else

answer = raw_input("2+2 = ")
if answer == "4":
    print "Correct"
else:
    print "Wrong answer, let's try something easier"
    answer = raw_input("1+1 = ")

    if answer == "2":
        print "Correct!"
    else:
        print "False"
于 2013-02-27T23:27:09.700 回答
2

您可以将代码放在函数中,并在满足任何给定条件后立即返回:

def func():
    answer = raw_input("2+2 = ")
    if answer == "4":
        print "Correct"
        return
    else:
        print "Wrong answer, let's try something easier"
        answer = raw_input("1+1 = ")
    if answer == "2":
        print "Correct!"
    else:
        print "False"

输出:

>>> func()
2+2 = 4
Correct
>>> func()
2+2 = 3
Wrong answer, let's try something easier
1+1 = 2
Correct!
于 2013-02-27T23:30:49.550 回答