一、变量
1.变量名组成:字母、数字、下划线;
2.不能数字开头;不能是关键字,如:'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield;
3.不要和python内置函数或类同名;
4.全局变量:一般使用大写字母命名,可在全局作用域调用;
5.局部变量:一般使用小写字母命名,只在局部作用域调用;在局部作用域中,优先读取局部变量,能读取全局变量,无法对全局变量重新赋值,但是对于可变类型,可以对内部元素进行操作;
NAME = ["allen","tsui"] def test(): NAME.append('yingjay') print(NAME) print(NAME) test() print(NAME) 输出: ['allen', 'tsui'] ['allen', 'tsui', 'yingjay'] ['allen', 'tsui', 'yingjay']
6.在函数定义中,函数体中使用global VAR表示在局部作用域中可修改全局变量并生效;global VAR语句需在变量赋值修改前定义;
NAME = "allen" def test(): global NAME print(NAME) NAME = "tsui" print(NAME) print(NAME) test() print(NAME) 输出: allen allen tsui tsui
NAME = "allen" def test(): NAME = "tsui" global NAME print(NAME) print(NAME) test() print(NAME) 输出: SyntaxError: name 'NAME' is assigned to before global declaration
7.nonlocal VAR类似于global,不过是指定上一级变量,如果没有就继续往上直到找到为止;
NAME = "allen" def test(): NAME = "tsui" print(NAME) def test1(): nonlocal NAME NAME = "yingjay" print(NAME) test1() print(NAME) print(NAME) test() print(NAME) 输出: allen tsui yingjay yingjay allen
二、运算符
1.字符串加法
a = "allen" b = "tsui" print(a+b) 输出: allentsui
2.字符串乘法
a = "allen" print(a * 3) 输出: allenallenallen
3.数字运算:加+、减-、乘*、除/、次方**、取余%、取商//
print(10+20) # 加 print(10-20) # 减 print(10*20) # 乘 print(120/20) # 除 print(2 ** 3) # 次方 print(10 % 3) # 取余 print(10 // 3) # 取商 输出: 30 -10 200 6.0 8 1 3
4.比较运算:大于>、小于<、等于=、不等于!=、大于等于>=、小于等于<=
5.逻辑运算:and、or、not
6.成员运算:in、not in
7.赋值运算:==、+=、-=、*=、/=
浙公网安备 33010602011771号