0

The problem with this code is that if you input anything other than "bob" first, when you finally input "bob", the main function will print None instead. Please run this code to fully understand what i'm having trouble with and to provide me some answers.

def main(name):
    print name

def x():
    name = raw_input()
    if name == "bob":
        return name
    else:
        print "error"
        x()

main(x())
1
  • This is happening because the call to x() in your code creates a recursion when "bob" is not entered. The function that pops off the call stack first your first incorrect input (not "bob"), in which case x returns nothing, or None. I would look into different ways of doing validation (use a while loop instead of using recursion here), this looks confusing. Commented Nov 19, 2015 at 8:27

2 Answers 2

3

Don't use recursion here. A simple while loop is sufficient.

def get_name_must_be_bob():
    while True:
        name = raw_input("Enter name: ")
        if name.lower() == "bob":   # "Bob", "BOB" also work...
            return name

        # `else` is not necessary, because the body of the `if` ended in `return`
        # (we can only get here if name is not Bob)

        print "Are you sure you're not Bob? Try again."

def main():
    name = get_name_must_be_bob()
    print "Hello, " + name


if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

Comments

0

You do not return a value in the "error" case. Change the x() to return x()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.