1

Using try, except inside a function in the following code producing a correct result.

def try_function():
    try:
        hrs = float(raw_input("Enter Hours: "))
        rate = float(raw_input("Enter Rate: "))
        return hrs * rate
    except:
        print "Values are non numeric"
        quit()

pay = try_function()
print pay

I got the following result:

Enter Hours: 20
Enter Rate: 10
200.0

While if i change the code to the following i get not result:

def try_function():
    try:
        hrs = float(raw_input("Enter Hours: "))
        rate = float(raw_input("Enter Rate: "))
    except:
        print "Values are non numeric"
        quit()
    return hrs * rate

pay = try_function()
print pay

Here what i get :

Enter Hours: 20
Enter Rate: 10

I don't know why i am not getting the value 200, and which way is better the first or the second?

Thank you.

19
  • 1
    Works as expected for me in python 2.7.3 on debian linux. which version of python are you using? Commented May 5, 2014 at 0:52
  • 1
    Works fine at repl.it/languages/Python. Commented May 5, 2014 at 0:53
  • i am using Python 2.7, and Windows Xp Commented May 5, 2014 at 0:55
  • 1
    note that using a bare except: is usually a very bad idea, as it will also catch special exceptions like KeyboardInterrupt and StopIteration. you almost always want except Exception:, or in this case, a more specific type like except ValueError:. Commented May 5, 2014 at 0:58
  • I agree with you and i thank you for the advice, but i have spent really considerable time trying to understand why i am getting a result in the first case while not result in the second one. Commented May 5, 2014 at 1:01

1 Answer 1

2

Perhaps you have an issue with mixing of tabs and spaces for indentation. Check if your indentation is consistent.

For example, if some lines are indented with tabs, and some with spaces, then visually the indentation might look correct, but Python could interpret the indentation differently than the way it appears in your editor.

You can try running Python with the -t option, which will give you a warning if there is a mix of tabs & spaces indentation. E.g.:

python -t myprogram.py
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.