Home > Blockchain >  Python Try and Except
Python Try and Except

Time:04-30

So recently, I learned something new which is Try and Except, and I still can't really get how it functions. Here is simple code of block. I would like some explanation on how this codes will run. Dish here refers to an item from dictionary. Note : Either ValueError or KeyError can be raised.

try:
    return dish["name"].index(cost["$"])
except KeyError:
    return None

CodePudding user response:

let's assume you have two dictionaries:

dish = {"name": ["A", "B", "C", "D"]}
cost = {"$": "A"} # It should be any value in A,B,C,D else it will raise Value Error for dish["name"].index(cost["$"])

Now if you want to raise ValueError Then you should search the index of value that does not exist in the list in your case

if I try to do this:

# return dish["name"].index(cost["$"]) $ This will raise ValueError if
# cost['$']= "E" because "E" does not exist in dish["name"] list so it will raise value error

Let me know if it explains your use case.

CodePudding user response:

Quick example but see https://docs.python.org/3/tutorial/errors.html for more info.

Your code will "try" and run the line

    return dish["name"].index(cost["$"])

and if there is a ValueError then it will execute the code

    return None

A ValueError is a mathematical error such as division by zero. If your code encounters a ValueError, it will run Return None, which does nothing. Try replacing return None with something like print("Exception") and force a value error to see what will happen.

  • Related