我正在嘗試用 Python 實作一個簡單的 Hello World 程式。以下代碼可以很好地列印“Hello World”:
def main(data=[72, 29, 7, 0, 3, -79, 55, 24, 3, -6, -8]):
print(chr(data[0]), end="")
if len(data) > 1:
data[0] = data.pop(1)
raise Exception()
if __name__ == "__main__":
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
main()
...但是當我嘗試在末尾添加一個感嘆號時,如下所示:
def main(data=[72, 29, 7, 0, 3, -79, 55, 24, 3, -6, -8, -67]):
if len(data) > 1:
data[0] = data.pop(1)
raise Exception()
if __name__ == "__main__":
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
try:
main()
except Exception as e:
main()
...我得到一個Fatal Python error: XXX block stack overflow.
我嘗試添加更多 try/except 子句來捕獲塊堆疊溢位錯誤,但似乎沒有任何效果。塊堆疊到底是什么,為什么這種簡單的方法行不通?
uj5u.com熱心網友回復:
這是一個已“修復”的已知問題。但是,更改的更多是確切的錯誤訊息和嵌套深度限制。Python 并不真正打算支持任意深度的靜態嵌套。如果這樣做是微不足道的,但它不是微不足道的。我希望大多數程式員不會將這種深度嵌套視為“一場噩夢”,而不是“一種直接的方法”;-)
uj5u.com熱心網友回復:
使用 Python 3.10,我收到一條更不言自明的錯誤訊息:
try:
^^^^
SyntaxError: too many statically nested blocks
你鉆得太貪心,太深了。重組代碼以不讓這么多塊相互嵌套。
uj5u.com熱心網友回復:
我只能猜測您正在嘗試嘗試并理解 Python 中的例外處理。也許這會有所幫助:
def main(data=[72, 29, 7, 0, 3, -79, 55, 24, 3, -6, -8, -67]):
print(chr(data[0]), end="")
if len(data) > 1:
data[0] = data.pop(1)
raise Exception()
if __name__ == '__main__':
while True:
try:
main()
# when the *data* list contains only one element
# main() will implicitly return None - i.e., no exception
break
except Exception:
pass
輸出:
Hello world!
話雖如此,您的代碼可以簡化為:
def main(data=[72, 29, 7, 0, 3, -79, 55, 24, 3, -6, -8, -67]):
print(chr(data[0]), end="")
data[0] = data.pop(1)
if __name__ == '__main__':
while True:
try:
main()
except IndexError:
break
uj5u.com熱心網友回復:
不要將代碼復雜化,只需將整個代碼寫在紙上,您就可以輕松擺脫錯誤!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454113.html
