Python基础问题

目录

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”)

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

if spam == 42    print('Hello!')
2)使用 = 而不是 ==(导致“SyntaxError: invalid syntax”)

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

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

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

print('Hello!')    print('Howdy!') 或者:if spam == 42:    print('Hello!')  print('Howdy!') 或者:if spam == 42:print('Hello!')

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

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

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

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

spam = ['cat', 'dog', 'mouse']for i in range(spam):    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)

而你实际想要这样做:

spam = 'I have a pet cat.'spam = spam[:13] + 'r' + spam[14:]print(spam)
6)尝试连接非字符串值与字符串(导致 “TypeError: Can’t convert ‘int’ object to str implicitly”)

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

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

而你实际想要这样做:

numEggs = 12print('I have ' + str(numEggs) + ' eggs.')或者numEggs = 12print('I have %s eggs.' % (numEggs))
7)在字符串首尾忘记加引号(导致“SyntaxError: EOL while scanning string literal”)

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

print(Hello!')或者print('Hello!)或者myName = 'Al'print('My name is ' + myName + . How are you?')
8)变量或者函数名拼写错误(导致“NameError: name ‘fooba’ is not defined”)

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

foobar = 'Al'print('My name is ' + fooba)或者spam = ruond(4.2)或者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”)

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

spam = ['cat', 'dog', 'mouse']print(spam[6])
11)使用不存在的字典键值(导致“KeyError:‘spam’”)

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

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}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”)

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

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

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

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

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

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

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

也许这才是你想做:

spam = list(range(10))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)判断路径是文件还是文件夹 判断是否存在、获取文件大小
#### 判断是文件还是文件夹import osif os.path.isdir(path):    print "it's a directory"elif os.path.isfile(path):    print "it's a normal file"else:    print "it's a special file(socket,FIFO,device file)"  #### 判断文件,文件夹是否存在import os>>> os.path.exists('d:/assist')True>>> os.path.exists('d:/assist/getTeacherList.py')True  #### 获取文件大小import osos.path.getsize(path)
23)判断参数为Nonetype类型或空值

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

判断方式如下:

if hostip is None:         print "no hostip,is nonetype"  elif hostip:         print "hostip is not null"    else:         print " hostip is null" 
24)含下标列表遍历
for i,value in enumerate(['A', 'B', 'C'])     print(i,value) 
25)数组 list 添加、修改、删除、长度

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

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

26)字典 添加、修改、删除
一)增加一个或多个元素d = {'a': 1}d.update(b=2)  #也可以 d.update({‘b’: 2})print(d)-->{'a': 1, 'b': 2} d.update(c=3, d=4)print(d)-->{'a': 1, 'c': 3, 'b': 2, 'd': 4} d['e'] = 5print(d)-->{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} d.update({'f': 6, 'g': 7})  #即d.update(字典)print(d)-->{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6}  二)删除一个或多个元素x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}x.pop(1)   #pop()()里为需要删除的key值;即若x.pop(3),则删除3:4元素。print(x)-->{0: 0, 2: 1, 3: 4, 4: 3} x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}del x[1]print(x)-->{0: 0, 2: 1, 3: 4, 4: 3} def remove_key(d, key):r = dict(d)del r[key]return r x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}print(remove_key(x, 1))print(x)-->{0: 0, 2: 1, 3: 4, 4: 3}-->{0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
27)判断字典中是否存在某个键
#判断字典中某个键是否存在arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"} #使用 in 方法if "int" in arr:    print("存在")if "float" in arr.keys():    print("存在") #判断键不存在if "floats" not in arr:    print("不存在")if "floats" not in arr:    print("不存在")
28)代码换行
Python中一般是一行写完所有代码,如果遇到一行写不完需要换行的情况,有两种方法: 1.在该行代码末尾加上续行符“ \”(即空格+\);test = 'item_one' \'item_two' \'tem_three'输出结果:'item_oneitem_twotem_three' 2.加上括号,() {}  []中不需要特别加换行符:test2 = ('csdn ''cssdn')输出结果:csdn cssdn
29)判断文件是否存在的三种方法

1.使用os模块

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

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

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

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

  • 只检查文件

    import osos.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。

import osif os.access("/file/path/foo.txt", os.F_OK):    print "Given file path is exist." if os.access("/file/path/foo.txt", os.R_OK):    print "File is accessible to read" if os.access("/file/path/foo.txt", os.W_OK):    print "File is accessible to write" if os.access("/file/path/foo.txt", os.X_OK):    print "File is accessible to execute"

2.使用Try语句

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

语法:

open()

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

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

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

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

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

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

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

try:    f =open()    f.close()except IOError:    print "File is not accessible."

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

3. 使用pathlib模块

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

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

  • 检查路径是否存在
path = pathlib.Path("path/file")path.exist()
  • 检查路径是否是文件
path = pathlib.Path("path/file")path.is_file()
30)字符串分割多个分隔符

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

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

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

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

本文转自 https://blog.csdn.net/whatday/article/details/86519263,如有侵权,请联系删除。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值