1、字符串不能直接和数字相加,要用str()转一下;但是可以和数字相乘,用于表示多个字符串复制;字符串不能和浮点数直接结合,字符串可以和字符串直接相加;
2、输入函数用input(),默认是字符串 计算字符串长度用len()
3、注释用#
4、类型转换,int()整型,str()字符串类型,float()浮点类型
5、**是求指数值 //是整除 /是除法
6、判断变量类型,type(变量)
第二部分 控制流
1、not 非 and 与 or 或
2、range(开始,结束,步长) 注意:循环不包括‘结束’
3、import 函数 导入函数 from import是另一种导入形式,举例 from random import * 可以在使用random函数时不用加random.前缀
4、sys.exit()提前结束程序,需要import sys
第三部分 函数
1、def 函数名(入参):
2、关键字 print('hello',end='') 连接字符 print('cats','dogs','mice',sep=',')用 ','代替‘ ’
3、要想在函数中修改全局变量,需要在全局变量前加上global关键字
4、异常处理 try 和except
常用的异常类型
1 1、NameError:尝试访问一个未申明的变量 2 >>> v 3 NameError: name 'v' is not defined 4 5 2、ZeroDivisionError:除数为0 6 >>> v = 1/0 7 ZeroDivisionError: int division or modulo by zero 8 9 3、SyntaxError:语法错误 10 >>> int int 11 SyntaxError: invalid syntax (<pyshell#14>, line 1) 12 13 4、IndexError:索引超出范围 14 >>> List = [2] 15 >>> List[3] 16 Traceback (most recent call last): 17 File "<pyshell#18>", line 1, in <module> 18 List[3] 19 IndexError: list index out of range 20 21 5、KeyError:字典关键字不存在 22 >>> Dic = {'1':'yes', '2':'no'} 23 >>> Dic['3'] 24 Traceback (most recent call last): 25 File "<pyshell#20>", line 1, in <module> 26 Dic['3'] 27 KeyError: '3' 28 29 6、IOError:输入输出错误 30 >>> f = open('abc') 31 IOError: [Errno 2] No such file or directory: 'abc' 32 33 7、AttributeError:访问未知对象属性 34 >>> class Worker: 35 def Work(): 36 print("I am working") 37 >>> w = Worker() 38 >>> w.a 39 Traceback (most recent call last): 40 File "<pyshell#51>", line 1, in <module> 41 w.a 42 AttributeError: 'Worker' object has no attribute 'a' 43 44 8、ValueError:数值错误 45 >>> int('d') 46 Traceback (most recent call last): 47 File "<pyshell#54>", line 1, in <module> 48 int('d') 49 ValueError: invalid literal for int() with base 10: 'd' 50 51 9、TypeError:类型错误 52 >>> iStr = '22' 53 >>> iVal = 22 54 >>> obj = iStr + iVal; 55 Traceback (most recent call last): 56 File "<pyshell#68>", line 1, in <module> 57 obj = iStr + iVal; 58 TypeError: Can't convert 'int' object to str implicitly 59 60 10、AssertionError:断言错误 61 >>> assert 1 != 1 62 Traceback (most recent call last): 63 File "<pyshell#70>", line 1, in <module> 64 assert 1 != 1 65 AssertionError