新手初学Python最常犯的十个错误,其中有你么

栏目: Python · 发布时间: 7年前

内容简介:在 if、elif、else、for、while、class、def 语句后面忘记添加“:”if spam == 42

新手初学 <a href='https://www.codercto.com/topics/20097.html'>Python</a> 最常犯的十个错误,其中有你么

1. 忘记写冒号

在 if、elif、else、for、while、class、def 语句后面忘记添加“:”

if spam == 42

print('Hello!')

2. 误用 “=” 做等值比较

“=”是给变量赋值,“==”才是判断两个值是否相等:

score = 60

if score = 60:

print ('passed')

改正:

score = 60

if score == 60:

print ('passed')

3. 变量没有定义:

if age >= 18:

print ('adult')

print ('END')

会导致:NameError: name ‘age’ is not defined.

改正:

age = 20

if age >= 18:

print ('adult')

print ('END')

4. 字符串与非字符串连接

错误:

num = 12

print('I have ' + num+ ' apples.')

非字符串和字符串连接的时候,要将非字符串转换为字符串类型之后才能连接,改正:

num = 12

print('I have ' + str(num)+ ' apples.')

5. 列表的索引位置

习惯性地认为列表元素的位置是从1开始的:

spam = ['cat', 'dog', 'mouse']

print(spam[3])

列表元素的位置是从0开始的,所以第3个元素“mouse”的索引位置是2,改正:

spam = ['cat', 'dog', 'mouse']

print(spam[2])

6. 使用自增 “++” 自减 “—”

学过 c语言 或者 Java 的人会很习惯使用i++或者i—,但在Python中是没有自增自减操作符的:

spam = 0

spam++

这时可以使用 “+=” 来代替 “++”,改正:

spam = 0

spam += 1

7. 使用关键字命名变量

Python 3中一共33个关键字:

False,None,True,and,as,assert,break,class,continue,def,del,elif,else,except,finally,for,from,global,if,import,in,is,lambda,nonlocal,not,or,pass,raise,return,try,while,with,yield

自定义变量时,变量名不能和这些关键字重复。

8. 索引元素位置时忘记调用 len 方法

通过索引位置来获取列表元素时,忘记要先使用 len 函数来获取列表的长度:

fam = ['dad', 'mom', 'son']

for i in range(fam):

print(fam[i])

改正:

fam = ['dad', 'mom', 'son']

for i in range(len(fam)):

print(fam[i])

9. 函数中的局部变量赋值前被使用

num = 42

def myFunction():

print(num)

num = 100

myFunction()

第一行定义了一个全局变量num,同时函数myFunction( )也定义了一个同名的局部变量,但程序执行时是先查找局部变量的,所以在函数中找到num之后就不到外部查找了,此时就会出现print的时候变量num还没赋值的错误。

10. 缩进问题

和其他语言的语法最大的不同就是,Python不能用括号来表示语句块,也不能用开始或结束标志符来表示,而是靠缩进来区分代码块的。

常见的错误用法:

(1)

print('Hello')

print('World!')

错误是第二行的缩进会导致两个print语句是包含和被包含的关系,但他们两者是属于同一个代码块的,所以应该写成;

print('Hello')

print('World!')

(2)

if spam == 42:

print('Hello')

print('World!')

错误是第三行的缩进,改正的方法有两种,一是如果两个print语句是属于同一代码块的,应该改正为

if spam == 42:

print('Hello')

print('World!')

二是如果第三行的print语句是和if语句是同一级的,则改正为

if spam == 42:

print('Hello')

print('World!')

(3)在Python 3中,缩进的时候,不能Tab和空格混用,每个缩进层次应该选择只使用Tab或者只使用空格。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Google's PageRank and Beyond

Google's PageRank and Beyond

Amy N. Langville、Carl D. Meyer / Princeton University Press / 2006-7-23 / USD 57.50

Why doesn't your home page appear on the first page of search results, even when you query your own name? How do other web pages always appear at the top? What creates these powerful rankings? And how......一起来看看 《Google's PageRank and Beyond》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具