python语言常见问题

python语言常见问题

1. 编译错误

1.1. TabError: inconsistent use of tabs and spaces in indentation

C:\timer>python getAllTitles.py
  File "getAllTitles.py", line 192
    startTime = datetime.datetime.now()
                                      ^
TabError: inconsistent use of tabs and spaces in indentation
  • 在Sublime Text编辑器中检查代码发现:
    这里写图片描述
这个错误的原因是,在代码中用了tab键做缩进了,python和其他语言(c,c++,java)不同,它是用缩进来区分程序块。
解决方案就是:把Tab键换成4个空格。如下图所示:

这里写图片描述

2. 语法问题

2.1. try…finally 和 return之间的关系


def func():
    count = 0
    mark = 0
    try:
        mark = 1
        count += 5
        print(f"1. count = {count}, mark = {mark}")
    except Exception as e:
        mark = 2
        count += 5
        print(f"2. exception: count = {count}, mark = {mark}")
    else:
        mark = 3
        count += 9
        print(f"3. count = {count}, mark = {mark}")
        # 这个时候,其实已经把count=14, mark=3这两个值送入到return函数中
        # 然后再执行finally语句
        # 最后,再从return函数中出来
        return (count, mark)
    finally:
        mark = 4
        count += 11
        print(f"4. count = {count}, mark = {mark}")

if __name__ == "__main__":
    result = func()
    print(f"result = {result}")

# 打印结果
1. count = 5, mark = 1
3. count = 14, mark = 3
4. count = 25, mark = 4
result = (14, 3)
发布了73 篇原创文章 · 获赞 244 · 访问量 69万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章