如何解决错误:此代码无法访问 – 在PyCharm中

huangapple go评论156阅读模式
英文:

how to solve error :This code is unreachable - in pycharm

问题

这段代码给出了错误信息:"This code is unreachable"。原因是因为在函数myFunc中,无论if x条件是True还是False,都会在return语句之前返回结果,因此下面的print("hello world")语句永远不会被执行。这就是为什么编译器或解释器会报告代码不可达的错误。

英文:
x = True

def myFunc():
    if x:
        return "yes"
    else:
        return "false"

    print("hello world")
myFunc()

This code gave me error as: "This code is unreachable"

Please can you explain why this is ?

答案1

得分: 1

使用return关键字,def会在代码遇到return语句时停止执行。它将指定的值赋予函数,然后停止执行。在你的情况下,你在一个if/else条件语句中使用了bool类型。所以x必须是True或者False,而这两种情况都有一个return语句。如果你想在这之后做任何事情,你应该在原始函数之外调用它。

因此,有了这些说法:

x = True

def myFunc():
    if x:
        return "yes"
    else:
        return "false"

myFunc()
print("hello world")

希望对你有所帮助。

英文:

With return keywords, the def stops when the code runs into a return line. It assigns the specified value to the function, and then it will stop. In your case, you have a bool type on an if/else condition. So x must be True or False, and both cases have a return statement. If you want to do anything after that, you should call it outside the original function.

So, with that being said:

x = True

def myFunc():
    if x:
        return "yes"
    else:
        return "false"

myFunc()
print("hello world")

Hope this helps.

答案2

得分: 1

代码显示错误,是因为在myFunc()函数的返回语句之后存在print("hello world")语句。返回语句用于退出函数并返回一个值。在函数的同一块内,在返回语句之后的任何代码都将无法访问并且不会被执行。

x = True

def myFunc():
    if x:
        print("hello world")
        return "yes"
    else:
        return "false"

result = myFunc()
print(result)
英文:

The code is showing an error because of the presence of the print("hello world") statement after the return statement in the myFunc() function. The return statement is used to exit the function and return a value. Any code after the return statement within the same block of the function will be unreachable and will not be executed.

x = True

def myFunc():
    if x:
        print("hello world")
        return "yes"
    else:
        return "false"

result = myFunc()
print(result)

huangapple
  • 本文由 发表于 2023年7月20日 09:56:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定