今天看啥  ›  专栏  ›  Python入门与进阶

Python最容易掉进去的10个坑

Python入门与进阶  · 公众号  ·  · 2018-09-04 12:39
相比于其他语言,Python的语法比较简单易学,但一旦不注意细节,刚入门的新手很容易就会掉进语法错误的坑里。1. 忘记写冒号在 if、elif、else、for、while、class、def 语句后面忘记添加“:”if spam == 42    print('Hello!')2. 误用 “=” 做等值比较“=”是给变量赋值,“==”才是判断两个值是否相等:score = 60if score = 60:    print ('passed')改正:score = 60if score == 60:    print ('passed')3. 变量没有定义:if age >= 18:    print ('adult')print ('END')会导致:NameError: name ‘age’ is not defined.改正:age = 20if age >= 18:    print ('adult')print ('END')4. 字符串与非字符串连接错误:num = 12print('I have ' + num+ ' apples.')非字符串和字符串连接的时候,要将非字符串转换为字符串类型之后才能连接,改正:num = 12print('I hav ………………………………

原文地址:访问原文地址
快照地址: 访问文章快照