user2113324
user2113324

Reputation:

Is there an "ignore" function for Python 2.7?

total newbie here.

So is there any way to stop a functioning from being executed if certain condition is met?

Here is my source code:

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"

So basically, if I put 4 on the first question, I will get the "False" comment from the "else" function below. I want to stop that from happening if 4 is input on the first question.

Upvotes: 2

Views: 5174

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

You can place the code inside a function and return as soon any given condition is met:

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"

output:

>>> func()
2+2 = 4
Correct
>>> func()
2+2 = 3
Wrong answer, let's try something easier
1+1 = 2
Correct!

Upvotes: 2

Bill the Lizard
Bill the Lizard

Reputation: 405965

Indentation level is significant in Python. Just indent the second if statement so it's a part of the first 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"

Upvotes: 3

Related Questions