Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python SQLAlchemy Basics Working with SQLAlchemy Setting Up Our App

While True clause causes an infinite loop.

Hi. In the video, Megan makes this loop. I've checked it several times to make sure it isn't a typo on my part. When she runs this loop, it shows the menu and question once and waits for input. When I run this code, the 1-5 menu options run infinitely until it throws and error, and never reaches the "choice" variable.

It actually makes more sense to me that an infinite loops would break this, and I can think of fixes, but I'm wondering why this runs the way she wants it to, but mine breaks. She starts this around 36 secs into the video, and runs the program at 1:50.

def menu():
    while True:
        print('''
        \nPROGRAMMING BOOKS
        \r1) Add a Book
        \r2) View All Books
        \r3) Search for a Book
        \r4) Book Analysis
        \r5) Exit
        ''')
    choice = input('What would you like to do?  ')
    if choice in [1, 2, 3, 4, 5]:
        return choice
    else:
        input('Please choose an option by its number (1-5), listed above.')

2 Answers

Mel Rumsey
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree seal-36
Mel Rumsey
Treehouse Staff

Hey amandae You are close! Currently your

    choice = input('What would you like to do?  ')
    if choice in [1, 2, 3, 4, 5]:
        return choice
    else:
        input('Please choose an option by its number (1-5), listed above.')

is outside of your while loop. You'll need to make sure this code is inside of the loop! Otherwise, your code looks good! :)

<facepalm>
Thank you. It seems so easy once you say it!

For anyone else who can't see it...

When Megan writes her code, the choice = input... is a tab closer to the edge than the string above it. In my code, the two will be vertically aligned. This is simply a style difference between VSCode and PyCharm. Both are fine for the string, but it means PyCharm code will line up differently. I was moving this line of code back a tab, to match hers, while not noticing I was a tab back already.