Python 2.7是否有“忽略”功能?

时间:2013-02-27 23:23:28

标签: python

这里的新手。

如果满足某些条件,有没有办法阻止执行功能?

这是我的源代码:

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”函数中得到“假”评论。如果在第一个问题上输入4,我想阻止这种情况发生。

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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!