Will
Will

Reputation: 25

Python Issue: Try and Excepts with if

This is probably very basic but I am trying to trigger the Except to run if cointype() is not within the dictionary coin_int but it jumps straight out of the if condition without using the Except even if a value error is met? Thanks for any help.

try:
    coin_type = input("Input your coin: 1p, 2p, 5p etc...  ")
    if coin_type in coin_int:
        print("That value is recognised inside the list of known coin types")

except ValueError:
    print("That value of coin is not accepted, restarting...")

Upvotes: 1

Views: 311

Answers (3)

John Smith
John Smith

Reputation: 1117

Firstly your except will never be reached... you don't "try" anything that will raise ValueError exception... Let me first show how to this, and then basically say that in this case you don't gain anything by using try/except:

coin_int = ("1p", "2p", "5p")
while True:
    coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
    try:
        coin_int.index(coin_type)
        print("value accepted, continuouing...")
        break
    except ValueError:
        print("That value of coin is not accepted, try again and choose from", coin_int)

But this is equivalent and in this case just as efficient (if not better actually both in performance and readability):

coin_int = ("1p", "2p", "5p")
while True:
    coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
    if coin_type in coin_int:
        print("value accepted, continuouing...")
        break
    else:
        print("That value of coin is not accepted, try again and choose from", coin_int)

If you really want to stop program execution then do any of the following in the except:

  • raise to raise the excception caught with default message
  • raise ValueError("That value of coin is not accepted, try again and choose from", coin_int) which also can be used in the else to raise the specific exception with custom message

Upvotes: 2

Wasi Ahmad
Wasi Ahmad

Reputation: 37691

Your program should looks like this. (i am giving example through a list instead of dictionary)

coin_int = ['1p', '2p', '3p', '4p', '5p']
try:
    coin_type = '6p'
    if coin_type in coin_int:
        print("That value is recognised inside the list of known coin types")
    else:
        raise ValueError("wrong coin type")
except ValueError as error:
    print("That value of coin is not accepted, restarting..." + repr(error))

Upvotes: 0

blue note
blue note

Reputation: 29071

you want to raise an exception. Just

raise ValueError("wrong coin type")

Upvotes: 3

Related Questions