简体   繁体   English

使用try,但在Python中的函数内部除外

[英]using try, except inside a function in Python

Using try, except inside a function in the following code producing a correct result. 使用try,但以下代码中的函数内部除外,可以产生正确的结果。

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? 我不知道为什么我没有得到值200,第一种或第二种哪种方法更好?

Thank you. 谢谢。

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. 例如,如果某些行用制表符缩进,有些行用空格缩进,则在视觉上,缩进看起来可能是正确的,但是Python解释缩进的方式与其在编辑器中的显示方式不同。

You can try running Python with the -t option, which will give you a warning if there is a mix of tabs & spaces indentation. 您可以尝试使用-t选项运行Python,如果选项卡和空格缩进混合使用,则会发出警告。 Eg: 例如:

python -t myprogram.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM