#๐Ÿ”’ Touch up for my return_book function

33 messages ยท Page 1 of 1 (latest)

glass spindle
#

Hello everyone, I'm back again. I've got a very minor problem! Make it rhyme.

# Now dictionaries are involved, everything becomes way easier.
def return_book():
    while True:
        # Turns out books dictionary into a list, called genres
        genres = list(books)
        # prints out the selection menu
        print("Please enter a number to select your genre. To exit, enter 0: ")
        # uses enumeration, sets start to 1 so that it starts at 1 and not 0. We will need to subtract 1 from their answer for genre.
        for index, genre in enumerate(genres, 1):
            # F string prints our index and genre
            print(f'{index}. {genre}')
        selection = int(input('> '))
        if selection == 0:
            print("Exit!")
            break
        # Len is the count of the objects, so if we put a number higher than the count...it prints an error.
        elif selection > len(genres):
            print("Invalid!")
        else:
            # selected_genre becomes a key with which we can access our dictionary
            print("This was a valid selection.")
            # subtracts 1 from the genres so that user input lines up with dictionary.
            selected_genre = genres[selection - 1]
            if books[selected_genre] < MAXIMUM_STOCK[selected_genre]:
                books[selected_genre] += 1
                # Our f-string lets us print the genre and how many books are in it.
                print(f"You have successfully returned a {selected_genre} book.")
                print(f"You now have {books[selected_genre]} {selected_genre} book(s)")
                break
            else:
                print(f"Error 5 ({selection}): Returning exceeds inventory maximum.")```

I need to fit an `except ValueError` in here somewhere, I think, so that if someone prints some garbage text, it doesn't break and go to `main_menu` but instead restarts the loop. Don't know how to fit it here though, cheers!
timber ledgeBOT
#

@glass spindle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

glass spindle
cobalt slate
#

hello again

#

the try needs to come just before getting your selection input

#

and then inside the except, you can use a continue which sends the loop back to the top

#
try:
    selection = int(input('> '))
except ValueError:
    continue
#

simple as that

glass spindle
#

Gnarly.

cobalt slate
#

everything else can stay exactly how it was

glass spindle
#

Beautiful. Let's run it and see how she looks.

cobalt slate
#

you could include an additional print in there if you want to inform the user that it was invalid and that they should only select a number from the list

glass spindle
#

Good idea.

#

Hmmm, running it seems to give me a TypeError.

cobalt slate
#

let's see it

glass spindle
#

Error message:

TypeError                                 Traceback (most recent call last)
File z:\uni stuff 2025\info1004\drewarmstrongassign1.py:189
    185     books[genre] = initial_inventory(genre, stock)
    188 # Runs our main_menu function after the initial input.
--> 189 main_menu()

File z:\uni stuff 2025\info1004\FILENAME.py:41, in main_menu()
     39     borrow_book()
     40 elif menu_option == 2:
---> 41     return_book()
     42 elif menu_option == 3:
     43     # Runs analyse_stock 4 times, with the parameters set up beforehand, making the analyse_stock function easier
     44     for genre, stock in books.items():

File z:\uni stuff 2025\info1004\FILENAME.py:111, in return_book()
    109 try: 
    110     selection = int(input('> '))
--> 111 except ValueError():
    112     print("Error 1 (3): Please only enter numbers.")
    113     continue

TypeError: catching classes that do not inherit from BaseException is not allowed```
Error.
cobalt slate
#

you shouldn't have () after ValueError

#

just except ValueError

glass spindle
#

Good catch.

#
def return_book():
    while True:
        # Turns out books dictionary into a list, called genres
        genres = list(books)
        # prints out the selection menu
        print("Please enter a number to select your genre. To exit, enter 0: ")
        # uses enumeration, sets start to 1 so that it starts at 1 and not 0. We will need to subtract 1 from their answer for genre.
        for index, genre in enumerate(genres, 1):
            # F string prints our index and genre
            print(f'{index}. {genre}')
        try: 
            selection = int(input('> '))
        except ValueError:
            print("Error 1 (3): Please only enter numbers.")
            continue
            if selection == 0:
                print("Exit!")
                break```

Here's my code now, after fixing that.
#

Works!

cobalt slate
#

everything else shouldn't be indented under the except

glass spindle
#

Good catch.

#

Do you know if Spyder has a method to just mass un-indent?

cobalt slate
#

usually shift+tab works in IDE

glass spindle
#

Cheers.

#

Anyway. We have it working!

cobalt slate
#

Nice! Anyways I gotta run!

glass spindle
#

Ciao bella. Should be easy to copy all this over for my borrow function given basically everything is the same.

#

Yep, it's all working!

#

!close

timber ledgeBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.