当前位置:   article > 正文

Python基础问题_for 循环unexpected indent

for 循环unexpected indent

目录

1)忘记在 if , elif , else , for , while , class ,def 声明末尾添加 :(导致 “SyntaxError :invalid syntax”)

2)使用 = 而不是 ==(导致“SyntaxError: invalid syntax”)

3)错误的使用缩进量。(导致“IndentationError: unexpected indent”、“IndentationError: unindent does not match any outer indentation level”以及“IndentationError: expected an indented block”)

4)在 for 循环语句中忘记调用 len() (导致“TypeError: ‘list’ object cannot be interpreted as an integer”)

5)尝试修改string的值(导致“TypeError: ‘str’ object does not support item assignment”)

6)尝试连接非字符串值与字符串(导致 “TypeError: Can’t convert ‘int’ object to str implicitly”)

7)在字符串首尾忘记加引号(导致“SyntaxError: EOL while scanning string literal”)

8)变量或者函数名拼写错误(导致“NameError: name ‘fooba’ is not defined”)

9)方法名拼写错误(导致 “AttributeError: ‘str’ object has no attribute ‘lowerr‘”)

10)引用超过list最大索引(导致“IndexError: list index out of range”)

11)使用不存在的字典键值(导致“KeyError:‘spam’”)

12)尝试使用Python关键字作为变量名(导致“SyntaxError:invalid syntax”)

13)在一个定义新变量中使用增值操作符(导致“NameError: name ‘foobar’ is not defined”)

14)在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)(导致“UnboundLocalError: local variable ‘foobar’ referenced before assignment”)

15)尝试使用 range()创建整数列表(导致“TypeError: ‘range’ object does not support item assignment”)

16)不错在 ++ 或者 — 自增自减操作符。(导致“SyntaxError: invalid syntax”)

17)忘记为方法的第一个参数添加self参数(导致“TypeError: myMethod() takes no arguments (1 given)”)

18)inconsistent use of tabs and spaces in indentation

19)SyntaxError: non-keyword arg after keyword arg”的语法错误

20)python 运行时候命令行导入其它模块

21)python注释

22)判断路径是文件还是文件夹 判断是否存在、获取文件大小

23)判断参数为Nonetype类型或空值

24)含下标列表遍历

25)数组 list 添加、修改、删除、长度

26)字典 添加、修改、删除

27)判断字典中是否存在某个键

28)代码换行

29)判断文件是否存在的三种方法

30)字符串分割多个分隔符

 


 

1)忘记在 if , elif , else , for , while , class ,def 声明末尾添加 :(导致 “SyntaxError :invalid syntax”)

该错误将发生在类似如下代码中:

  1. if spam == 42
  2. print('Hello!')

 

2)使用 = 而不是 ==(导致“SyntaxError: invalid syntax”)

= 是赋值操作符而 == 是等于比较操作。该错误发生在如下代码中:

  1. if spam = 42:
  2. print('Hello!')

 

3)错误的使用缩进量。(导致“IndentationError: unexpected indent”、“IndentationError: unindent does not match any outer indentation level”以及“IndentationError: expected an indented block”)

记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。该错误发生在如下代码中:

  1. print('Hello!')
  2. print('Howdy!')
  3. 或者:if spam == 42:
  4. print('Hello!')
  5. print('Howdy!')
  6. 或者:if spam == 42:
  7. print('Hello!')

解决方法 使用editplus正则替换 \t为4空格 再把其他非法缩进全局替换为4空格 可以用vi观察校对

 

4)在 for 循环语句中忘记调用 len() (导致“TypeError: ‘list’ object cannot be interpreted as an integer”)

通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。

该错误发生在如下代码中:

  1. spam = ['cat', 'dog', 'mouse']
  2. for i in range(spam):
  3. print(spam[i])

 

5)尝试修改string的值(导致“TypeError: ‘str’ object does not support item assignment”)

string是一种不可变的数据类型,该错误发生在如下代码中:

spam = 'I have a pet cat.'spam[13] = 'r'print(spam)

而你实际想要这样做:

  1. spam = 'I have a pet cat.'spam = spam[:13] + 'r' + spam[14:]
  2. print(spam)

 

6)尝试连接非字符串值与字符串(导致 “TypeError: Can’t convert ‘int’ object to str implicitly”)

该错误发生在如下代码中:

numEggs = 12print('I have ' + numEggs + ' eggs.')

而你实际想要这样做:

  1. numEggs = 12print('I have ' + str(numEggs) + ' eggs.')
  2. 或者
  3. numEggs = 12print('I have %s eggs.' % (numEggs))

 

7)在字符串首尾忘记加引号(导致“SyntaxError: EOL while scanning string literal”)

该错误发生在如下代码中:

  1. print(Hello!')
  2. 或者
  3. print('Hello!)
  4. 或者
  5. myName = 'Al'print('My name is ' + myName + . How are you?')

 

8)变量或者函数名拼写错误(导致“NameError: name ‘fooba’ is not defined”)

该错误发生在如下代码中:

  1. foobar = 'Al'print('My name is ' + fooba)
  2. 或者
  3. spam = ruond(4.2)
  4. 或者
  5. spam = Round(4.2)

 

9)方法名拼写错误(导致 “AttributeError: ‘str’ object has no attribute ‘lowerr‘”)

该错误发生在如下代码中:

spam = 'THIS IS IN LOWERCASE.'spam = spam.lowerr()

 

10)引用超过list最大索引(导致“IndexError: list index out of range”)

该错误发生在如下代码中:

  1. spam = ['cat', 'dog', 'mouse']
  2. print(spam[6])

 

11)使用不存在的字典键值(导致“KeyError:‘spam’”)

该错误发生在如下代码中:

  1. spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
  2. print('The name of my pet zebra is ' + spam['zebra'])

 

12)尝试使用Python关键字作为变量名(导致“SyntaxError:invalid syntax”)

Python关键不能用作变量名,该错误发生在如下代码中:

class = 'algebra'

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

 

13)在一个定义新变量中使用增值操作符(导致“NameError: name ‘foobar’ is not defined”)

不要在声明变量时使用0或者空字符串作为初始值,这样使用自增操作符的一句spam += 1等于spam = spam + 1,这意味着spam需要指定一个有效的初始值。

该错误发生在如下代码中:

spam = 0spam += 42eggs += 42

 

14)在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)(导致“UnboundLocalError: local variable ‘foobar’ referenced before assignment”)

在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的,使用规则是:如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。

这意味着你不能在定义它之前把它当全局变量在函数中使用。

该错误发生在如下代码中:

  1. someVar = 42def myFunction():
  2. print(someVar)
  3. someVar = 100myFunction()

 

15)尝试使用 range()创建整数列表(导致“TypeError: ‘range’ object does not support item assignment”)

有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值。

该错误发生在如下代码中:

  1. spam = range(10)
  2. spam[4] = -1

也许这才是你想做:

  1. spam = list(range(10))
  2. spam[4] = -1

(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)

 

16)不错在 ++ 或者 — 自增自减操作符。(导致“SyntaxError: invalid syntax”)

如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 — 自增自减一个变量。在Python中是没有这样的操作符的。

该错误发生在如下代码中:

spam = 1spam++

也许这才是你想做的:

spam = 1spam += 1

 

17)忘记为方法的第一个参数添加self参数(导致“TypeError: myMethod() takes no arguments (1 given)”)

该错误发生在如下代码中:

class Foo(): def myMethod(): print('Hello!') a = Foo() a.myMethod()

 

18)inconsistent use of tabs and spaces in indentation

这个报错就是混用了tab和4个空格造成的,检查代码,要不全部用tab,要不全部用4个空格,或者用idle编辑器校正,我常选择用notepad++进行代码缩进的检查。即可用消除该错误。
 

19)SyntaxError: non-keyword arg after keyword arg”的语法错误

在Python中,这两个是python中的可变参数,*arg表示任意多个无名参数,类型为tuple,**kwargs表示关键字参数,为dict,使用时需将*arg放在**kwargs之前,否则会有“SyntaxError: non-keyword arg after keyword arg”的语法错误

 

20)python 运行时候命令行导入其它模块

export PYTHONPATH="${PYTHONPATH}:/Users/wan/italki/italkimodel"

设置python环境变量后 在命令行就可以引入相应的模块了

 

21)python注释

井号(#)常被用作单行注释符号,在代码中使用#时,它右边的任何数据都会被忽略,当做是注释。
print 1 #输出1
#号右边的内容在执行的时候是不会被输出的。

在python中也会有注释有很多行的时候,这种情况下就需要批量多行注释符了。多行注释是用三引号'''   '''包含的

 

22)判断路径是文件还是文件夹 判断是否存在、获取文件大小

  1. #### 判断是文件还是文件夹
  2. import os
  3. if os.path.isdir(path):
  4. print "it's a directory"
  5. elif os.path.isfile(path):
  6. print "it's a normal file"
  7. else:
  8. print "it's a special file(socket,FIFO,device file)"
  9. #### 判断文件,文件夹是否存在
  10. import os
  11. >>> os.path.exists('d:/assist')
  12. True
  13. >>> os.path.exists('d:/assist/getTeacherList.py')
  14. True
  15. #### 获取文件大小
  16. import os
  17. os.path.getsize(path)

 

23)判断参数为Nonetype类型或空值

Nonetype和空值是不一致的,可以理解为Nonetype为不存在这个参数,空值表示参数存在,但是值为空

判断方式如下:

  1. if hostip is None:  
  2.        print "no hostip,is nonetype"  
  3. elif hostip:  
  4.        print "hostip is not null"    
  5. else:  
  6.        print " hostip is null" 

 

24)含下标列表遍历

  1. for i,value in enumerate(['A', 'B', 'C'])
  2. print(i,value)

 

25)数组 list 添加、修改、删除、长度

数组是一种有序的集合,可随时添加、删除其中的元素

  1. book = ['xiao zhu pei qi','xiao ji qiu qiu','tang shi san bai shou']// 定义book数组
  2. 1、添加 .insert/.append
  3. book.insert(0,'bu yi yang de ka mei la')//.insert(x,'xx') 在指定位置添加,x/第几位 , 'xx'/添加的内容
  4. book.append('e ma ma tong yao')  //.append('') 在末尾添加
  5. 2、修改元素
  6. book[2]='pei qi going swimming' //修改第二个位置为'pei qi going swimming'
  7. 3、删除 .pop() 
  8. book.pop() //删除末尾
  9. book.pop(X) //删除指定位置的内容,x=0-x 
  10. 4、得到长度 len(book)


 

26)字典 添加、修改、删除

  1. 一)增加一个或多个元素
  2. d = {'a': 1}
  3. d.update(b=2) #也可以 d.update({‘b’: 2})
  4. print(d)
  5. -->{'a': 1, 'b': 2}
  6. d.update(c=3, d=4)
  7. print(d)
  8. -->{'a': 1, 'c': 3, 'b': 2, 'd': 4}
  9. d['e'] = 5
  10. print(d)
  11. -->{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
  12. d.update({'f': 6, 'g': 7}) #即d.update(字典)
  13. print(d)
  14. -->{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6}
  15. 二)删除一个或多个元素
  16. x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
  17. x.pop(1) #pop(),()里为需要删除的key值;即若x.pop(3),则删除3:4元素。
  18. print(x)
  19. -->{0: 0, 2: 1, 3: 4, 4: 3}
  20. x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
  21. del x[1]
  22. print(x)
  23. -->{0: 0, 2: 1, 3: 4, 4: 3}
  24. def remove_key(d, key):
  25. r = dict(d)
  26. del r[key]
  27. return r
  28. x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
  29. print(remove_key(x, 1))
  30. print(x)
  31. -->{0: 0, 2: 1, 3: 4, 4: 3}
  32. -->{0: 0, 1: 2, 2: 1, 3: 4, 4: 3}

 

27)判断字典中是否存在某个键

  1. #判断字典中某个键是否存在
  2. arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
  3. #使用 in 方法
  4. if "int" in arr:
  5. print("存在")
  6. if "float" in arr.keys():
  7. print("存在")
  8. #判断键不存在
  9. if "floats" not in arr:
  10. print("不存在")
  11. if "floats" not in arr:
  12. print("不存在")

 

28)代码换行

  1. Python中一般是一行写完所有代码,如果遇到一行写不完需要换行的情况,有两种方法:
  2. 1.在该行代码末尾加上续行符“ \”(即空格+\);
  3. test = 'item_one' \
  4. 'item_two' \
  5. 'tem_three'
  6. 输出结果:'item_oneitem_twotem_three'
  7. 2.加上括号,() {}  []中不需要特别加换行符:
  8. test2 = ('csdn '
  9. 'cssdn')
  10. 输出结果:csdn cssdn

 

29)判断文件是否存在的三种方法

1.使用os模块

os模块中的os.path.exists()方法用于检验文件是否存在。

  • 判断文件是否存在
  1. import os
  2. os.path.exists(test_file.txt)
  3. #True
  4. os.path.exists(no_exist_file.txt)
  5. #False
  • 判断文件夹是否存在
  1. import os
  2. os.path.exists(test_dir)
  3. #True
  4. os.path.exists(no_exist_dir)
  5. #False

可以看出用os.path.exists()方法,判断文件和文件夹是一样。

其实这种方法还是有个问题,假设你想检查文件“test_data”是否存在,但是当前路径下有个叫“test_data”的文件夹,这样就可能出现误判。为了避免这样的情况,可以这样:

  • 只检查文件
    1. import os
    2. os.path.isfile("test-data")

通过这个方法,如果文件”test-data”不存在将返回False,反之返回True。

即是文件存在,你可能还需要判断文件是否可进行读写操作。

 

判断文件是否可做读写操作

使用os.access()方法判断文件是否可进行读写操作。

语法:

os.access(path, mode)

path为文件路径,mode为操作模式,有这么几种:

  • os.F_OK: 检查文件是否存在;

  • os.R_OK: 检查文件是否可读;

  • os.W_OK: 检查文件是否可以写入;

  • os.X_OK: 检查文件是否可以执行

该方法通过判断文件路径是否存在和各种访问模式的权限返回True或者False。

  1. import os
  2. if os.access("/file/path/foo.txt", os.F_OK):
  3. print "Given file path is exist."
  4. if os.access("/file/path/foo.txt", os.R_OK):
  5. print "File is accessible to read"
  6. if os.access("/file/path/foo.txt", os.W_OK):
  7. print "File is accessible to write"
  8. if os.access("/file/path/foo.txt", os.X_OK):
  9. print "File is accessible to execute"

 

2.使用Try语句

可以在程序中直接使用open()方法来检查文件是否存在和可读写。

语法:

open()

如果你open的文件不存在,程序会抛出错误,使用try语句来捕获这个错误。

程序无法访问文件,可能有很多原因:

  • 如果你open的文件不存在,将抛出一个FileNotFoundError的异常;

  • 文件存在,但是没有权限访问,会抛出一个PersmissionError的异常。

所以可以使用下面的代码来判断文件是否存在:

  1. try:
  2. f =open()
  3. f.close()
  4. except FileNotFoundError:
  5. print "File is not found."
  6. except PersmissionError:
  7. print "You don't have permission to access this file."

其实没有必要去这么细致的处理每个异常,上面的这两个异常都是IOError的子类。所以可以将程序简化一下:

  1. try:
  2. f =open()
  3. f.close()
  4. except IOError:
  5. print "File is not accessible."

使用try语句进行判断,处理所有异常非常简单和优雅的。而且相比其他不需要引入其他外部模块。

 

3. 使用pathlib模块

pathlib模块在Python3版本中是内建模块,但是在Python2中是需要单独安装三方模块。

使用pathlib需要先使用文件路径来创建path对象。此路径可以是文件名或目录路径。

  • 检查路径是否存在
  1. path = pathlib.Path("path/file")
  2. path.exist()
  • 检查路径是否是文件
  1. path = pathlib.Path("path/file")
  2. path.is_file()

 

30)字符串分割多个分隔符

python中.split()只能用指定一个分隔符

  1. text='3.14:15'
  2. print text.split('.')
  3. #结果如下:
  4. ['3', '14:15']

指定多个分隔符可以用re模块

  1. import re
  2. text='3.14:15'
  3. print re.split('[.:]', text)
  4. #结果如下:
  5. ['3', '14', '15']

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/847060
推荐阅读
相关标签
  

闽ICP备14008679号