Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

What am i missing here??

So im trying to create a simply game. I wrote this code to ensure that the player only input 1 or 2:

def FirstOrSecond():
    choice = ""
    print("Would you like to play first or second? 1/2")
    try:
        choice = int(input())
    except ValueError:
        print("You can only input 1 or 2!")
        FirstOrSecond()
    if choice != 1 and choice != 2:
        print("You can only input 1 or 2!")
        FirstOrSecond()
    else:
        return choice

Now the code works perfectly. If you input anything but 1 or 2 it will print the message, if you input 1 or 2 it will return it.. However, if you input something invalid first, and then input one or 2, it will out the message twice?? Can someone please explain to me why this is?

Just realised i can make this simpler:

def FirstOrSecond():
    print("Would you like to play first or second? 1/2")
    choice = input()
    if choice != "1" and choice != "2":
        print("You can only input 1 or 2!")
        FirstOrSecond()
    else:
        return choice

Still im curious about the original code

1 Answer

Stuart Wright
Stuart Wright
41,118 Points

The way you have coded it in your first post, you will have to enter as many valid inputs as invalid inputs that have preceded it before the program will exit. This is because the function is calling itself, and every time the function is called, a valid input is required to hand control back to the calling function.

So if you have entered 4 invalid inputs, the 4th nested function call has control. If you enter a valid input, control is handed back to the 3rd nested call. And so on.

This idea of a function calling itself is known as recursion, and it's an interesting topic to read up on. I first learned about this idea in the following, and I think it explains it well:

http://greenteapress.com/thinkpython2/html/thinkpython2006.html#sec62