Question

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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top