》注释
》》当行注视:# 被注释内容
》》多行注释:""" 被注释内容 """
》执行脚本传入参数
》》Python有大量的模块,从而使得开发Python程序非常简洁。类库有包括三中:
》》》Python内部提供的模块
》》》业内开源的模块
》》》程序员自己开发的模块
》》Python内部提供一个 sys 的模块,其中的 sys.argv 用来捕获执行执行python脚本时传入的参数
import sys print(sys.argv)
》pyc 文件
》》执行Python代码时,如果导入了其他的 .py 文件,那么,执行过程中会自动生成一个与其同名的 .pyc 文件,该文件就是Python解释器编译之后产生的字节码。
》》ps:代码经过编译可以产生字节码;字节码通过反编译也可以得到代码。
》》python语言的执行:代码编译得到字节码 ,虚拟机执行字节码并转换成机器码再后在处理器上执行
》变量
》》声明一个变量,变量名为: name,变量name的值为:"fury"
name = "fury"
》》 变量的作用:昵称,其代指内存里某个地址中保存的内容
》》变量定义的规则:
》》》变量名只能是 字母、数字或下划线的任意组合
》》》变量名的第一个字符不能是数字
》》》以下关键字不能声明为变量名
['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']
》变量的赋值
》》Python中变量的赋值同Java中字符串的操作差不多(详见Java字符串操作之常量池)
name1 = 'fury' name2 = 'fury' #同一个字符串可以被不同的变量引用 #name2 = name1 也是同样的效果 id1 = id(name1) #通过内置函数id()来读取变量的内存地址 id2 = id(name2) print(id1, id2) name2 = "warrior" #改变name2的值时name2的地址也变了,但是name1的值和地址都没有变 print(name1, name2) id1 = id(name1) #通过内置函数id()来读取变量的内存地址 id2 = id(name2) print(id1, id2) # PS: Python中字符串的赋值操作跟Java中的差不多 # x1 = 2 # x2 = x1 # id1 = id(x1) # id2 = id(x2) # print(x1, x2) # print(id1, id2) # # x2 = 12343 # print(x1, x2) # id1 = id(x1) # id2 = id(x2) # print(id1, id2)
》补充
》#print "hello" python2.x的print方法
》#python2.x不支持中文,如果有中文,需要添加 #_*_coding:utf-8_*_
在程序最开始指定解释器和编码规则
#!/usr/bin/env python # _*_coding:utf-8_*_
》输入
在3.0中input输入的默认都是字符串形式
name = input("Please input your name: ") print(name) # print(input("Please input your name: ")) #上面两行的优化版本 # 在3.0中input输入的默认都是字符串形式 name = input("Please input your name: ") age = int(input("Please input your age: ")) #convet string to int salary = float(input("Please input your salary: ")) print("name:", name) print("age:", age) print("slary", salary) msg = """ =====start===== Information of %s : name : %s age : %d salary : %f ======end======= """ %(name, name, age, salary) print(msg)
》流程控制和缩进
》》需求一:
# 提示输入用户名和密码
# 验证用户名和密码
# 如果错误,则输出用户名或密码错误
# 如果成功,则输出 欢迎,XXX!
name = input("Please input your name: ") passwords = input("Please input your passwords: ") if name == "fury" and passwords == 123: print("登录成功") else: print("用户名或者密码错误")
》》需求二
根据用户输入内容输出其权限
name = input("Please input your name: ") passwords = input("Please input your passwords: ") index = input("Please input you ID: ") if index.isdigit(): index = int(index) if passwords.isdigit(): passwords = int(passwords) if name == "fury" and passwords == 123: print("登录成功") if index == 1: print("你是博士") elif index == 2: print("你是硕士") elif index == 3: print("你是本科生") else: print("你是中学生") else: print("用户名或者密码错误")
》局部变量 VS 全局变量
1 name = "fury" 2 3 4 def test(): 5 name = "warrior" 6 print("test函数:", name) 7 8 9 def main(): 10 test() 11 print("main函数", name) 12 13 main()
》》当想要在局部对全局变量进行修改是需要用到 global 关键字
1 name = "fury" 2 3 4 def test(): 5 global name 6 name = "hello word" 7 print("test函数:", name) 8 9 10 def main(): 11 test() 12 print("main函数", name) 13 14 main()
》初识基本数据类型
2 是一个整数的例子。
长整数 不过是大一些的整数。
3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。
(-5+4j)和(2.3-4.6j)是复数的例子。
int(整型)
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
1 class int(object): 2 """ 3 int(x=0) -> int or long 4 int(x, base=10) -> int or long 5 6 Convert a number or string to an integer, or return 0 if no arguments 7 are given. If x is floating point, the conversion truncates towards zero. 8 If x is outside the integer range, the function returns a long instead. 9 10 If x is not a number or if base is given, then x must be a string or 11 Unicode object representing an integer literal in the given base. The 12 literal can be preceded by '+' or '-' and be surrounded by whitespace. 13 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 14 interpret the base from the string as an integer literal. 15 >>> int('0b100', base=0) 16 """ 17 def bit_length(self): 18 """ 返回表示该数字的时占用的最少位数 """ 19 """ 20 int.bit_length() -> int 21 22 Number of bits necessary to represent self in binary. 23 >>> bin(37) 24 '0b100101' 25 >>> (37).bit_length() 26 """ 27 return 0 28 29 def conjugate(self, *args, **kwargs): # real signature unknown 30 """ 返回该复数的共轭复数 """ 31 """ Returns self, the complex conjugate of any int. """ 32 pass 33 #两个实部相等,虚部互为相反数的复数互为共轭复数(conjugate #complex number) 34 def __abs__(self): 35 """ 返回绝对值 """ 36 """ x.__abs__() <==> abs(x) """ 37 pass 38 39 def __add__(self, y): 40 """ x.__add__(y) <==> x+y """ 41 pass 42 43 def __and__(self, y): 44 """ x.__and__(y) <==> x&y """ 45 pass 46 47 def __cmp__(self, y): 48 """ 比较两个数大小 """ 49 """ x.__cmp__(y) <==> cmp(x,y) """ 50 pass 51 52 def __coerce__(self, y): 53 """ 强制生成一个元组 """ 54 """ x.__coerce__(y) <==> coerce(x, y) """ 55 pass 56 57 def __divmod__(self, y): 58 """ 相除,得到商和余数组成的元组 """ 59 """ x.__divmod__(y) <==> divmod(x, y) """ 60 pass 61 62 def __div__(self, y): 63 """ x.__div__(y) <==> x/y """ 64 pass 65 66 def __float__(self): 67 """ 转换为浮点类型 """ 68 """ x.__float__() <==> float(x) """ 69 pass 70 71 def __floordiv__(self, y): 72 """ x.__floordiv__(y) <==> x//y """ 73 pass 74 75 def __format__(self, *args, **kwargs): # real signature unknown 76 pass 77 78 def __getattribute__(self, name): 79 """ x.__getattribute__('name') <==> x.name """ 80 pass 81 82 def __getnewargs__(self, *args, **kwargs): # real signature unknown 83 """ 内部调用 __new__方法或创建对象时传入参数使用 """ 84 pass 85 86 def __hash__(self): 87 """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" 88 """ x.__hash__() <==> hash(x) """ 89 pass 90 91 def __hex__(self): 92 """ 返回当前数的 十六进制 表示 """ 93 """ x.__hex__() <==> hex(x) """ 94 pass 95 96 def __index__(self): 97 """ 用于切片,数字无意义 """ 98 """ x[y:z] <==> x[y.__index__():z.__index__()] """ 99 pass 100 101 def __init__(self, x, base=10): # known special case of int.__init__ 102 """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 103 """ 104 int(x=0) -> int or long 105 int(x, base=10) -> int or long 106 107 Convert a number or string to an integer, or return 0 if no arguments 108 are given. If x is floating point, the conversion truncates towards zero. 109 If x is outside the integer range, the function returns a long instead. 110 111 If x is not a number or if base is given, then x must be a string or 112 Unicode object representing an integer literal in the given base. The 113 literal can be preceded by '+' or '-' and be surrounded by whitespace. 114 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 115 interpret the base from the string as an integer literal. 116 >>> int('0b100', base=0) 117 # (copied from class doc) 118 """ 119 pass 120 121 def __int__(self): 122 """ 转换为整数 """ 123 """ x.__int__() <==> int(x) """ 124 pass 125 126 def __invert__(self): 127 """ x.__invert__() <==> ~x """ 128 pass 129 130 def __long__(self): 131 """ 转换为长整数 """ 132 """ x.__long__() <==> long(x) """ 133 pass 134 135 def __lshift__(self, y): 136 """ x.__lshift__(y) <==> x<<y """ 137 pass 138 139 def __mod__(self, y): 140 """ x.__mod__(y) <==> x%y """ 141 pass 142 143 def __mul__(self, y): 144 """ x.__mul__(y) <==> x*y """ 145 pass 146 147 def __neg__(self): 148 """ x.__neg__() <==> -x """ 149 pass 150 151 @staticmethod # known case of __new__ 152 def __new__(S, *more): 153 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 154 pass 155 156 def __nonzero__(self): 157 """ x.__nonzero__() <==> x != 0 """ 158 pass 159 160 def __oct__(self): 161 """ 返回改值的 八进制 表示 """ 162 """ x.__oct__() <==> oct(x) """ 163 pass 164 165 def __or__(self, y): 166 """ x.__or__(y) <==> x|y """ 167 pass 168 169 def __pos__(self): 170 """ x.__pos__() <==> +x """ 171 pass 172 173 def __pow__(self, y, z=None): 174 """ 幂,次方 """ 175 """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ 176 pass 177 178 def __radd__(self, y): 179 """ x.__radd__(y) <==> y+x """ 180 pass 181 182 def __rand__(self, y): 183 """ x.__rand__(y) <==> y&x """ 184 pass 185 186 def __rdivmod__(self, y): 187 """ x.__rdivmod__(y) <==> divmod(y, x) """ 188 pass 189 190 def __rdiv__(self, y): 191 """ x.__rdiv__(y) <==> y/x """ 192 pass 193 194 def __repr__(self): 195 """转化为解释器可读取的形式 """ 196 """ x.__repr__() <==> repr(x) """ 197 pass 198 199 def __str__(self): 200 """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" 201 """ x.__str__() <==> str(x) """ 202 pass 203 204 def __rfloordiv__(self, y): 205 """ x.__rfloordiv__(y) <==> y//x """ 206 pass 207 208 def __rlshift__(self, y): 209 """ x.__rlshift__(y) <==> y<<x """ 210 pass 211 212 def __rmod__(self, y): 213 """ x.__rmod__(y) <==> y%x """ 214 pass 215 216 def __rmul__(self, y): 217 """ x.__rmul__(y) <==> y*x """ 218 pass 219 220 def __ror__(self, y): 221 """ x.__ror__(y) <==> y|x """ 222 pass 223 224 def __rpow__(self, x, z=None): 225 """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ 226 pass 227 228 def __rrshift__(self, y): 229 """ x.__rrshift__(y) <==> y>>x """ 230 pass 231 232 def __rshift__(self, y): 233 """ x.__rshift__(y) <==> x>>y """ 234 pass 235 236 def __rsub__(self, y): 237 """ x.__rsub__(y) <==> y-x """ 238 pass 239 240 def __rtruediv__(self, y): 241 """ x.__rtruediv__(y) <==> y/x """ 242 pass 243 244 def __rxor__(self, y): 245 """ x.__rxor__(y) <==> y^x """ 246 pass 247 248 def __sub__(self, y): 249 """ x.__sub__(y) <==> x-y """ 250 pass 251 252 def __truediv__(self, y): 253 """ x.__truediv__(y) <==> x/y """ 254 pass 255 256 def __trunc__(self, *args, **kwargs): 257 """ 返回数值被截取为整形的值,在整形中无意义 """ 258 pass 259 260 def __xor__(self, y): 261 """ x.__xor__(y) <==> x^y """ 262 pass 263 264 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 265 """ 分母 = 1 """ 266 """the denominator of a rational number in lowest terms""" 267 268 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 269 """ 虚数,无意义 """ 270 """the imaginary part of a complex number""" 271 272 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 273 """ 分子 = 数字大小 """ 274 """the numerator of a rational number in lowest terms""" 275 276 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 277 """ 实属,无意义 """ 278 """the real part of a complex number""" 279 280 int
跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。
注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。
float(浮点型)
浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
complex(复数)
复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。
"hello world"
》》万恶的字符串拼接:
1 name = "fury" 2 age = 23 3 print("The age of that fellow named %s is %d" %(name, age)) 4 print("The age of that fellow named {0} is {1}".format(*[name, age])) 5 print("The age of that fellow named {name} is {age}".format(**{"name" : "warrior","age" : 123}))
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ # strip() 方法会去掉字符串前后的空格、tab键、换行等等 print("===start===") # userName = input("Please input your name: ") # if userName.strip() == "fury": # print("Welcome to the city of Chongqing! ") #将字符串切成列表 print("===one===") name = "One,Two,Three" name1 = name.split(",") print(name1) # 将列表合成一个字符串 print("===two===") name2 = "|".join(name1) print(name2) # 判断一个字符串里面有没有空格 print("===three===") name3 = "fury wArrior" print(" " in name3) # 将字符串的首字母大写,其余的全部小写 print("===four===") print(name3.capitalize())
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ # 字符串的格式 print("===start===") msg = "Hello, {name}. Your age is {age}." print(msg.format(name = "fury", age = 123)) msg1 = "Hello, {0}. Your age is {1}." print(msg1.format("warrior",321)) # 切片 print("===one===") name = "Thinking in Java" print(name[0:8]) # len() 字符串长度 print("===two===") print(len(name)) # center() 将字符串放在自定宽度的中间,多余的位置用指定的字符进行填充 print("===three===") print(name.center(20,"-")) print(name.center(len(name) + 6,"&")) # find() 做出指定字符串的索引 print("===four===") print(name.find("T")) print(name.find("1234")) #没有返回 -1 # 判断输入的是否是数字 print("===five===") age = input("Please input your age: ") if age.isdigit(): age = int(age) else: print("Invalid input") print("===six===") name1 = "furywarrior" print(name1.endswith("warrior")) # 结束判断 print(name1.startswith("fury")) #开始判断 print(name1.upper()) #全部转换成大写 print(name1.lower()) #全部转换成小写
》列表
Python 中的list 就相当于 Java 中的数组;但是Python中的list可以存储不同的数据类型
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ # Python 中的list 就相当于 Java 中的数组;但是Python中的list可以存储不同的数据类型 name = ["fury", "warrior",1,2,3,4,"peter","bob"] print(name[1]) print(name[-1]) print(name[0:2]) #切片 注意:和Java一样,取首不取尾 print(name[-5:-1]) #没取到最后一个 ,原因:取首不取尾 print(name[-5:]) #不写后面这个参数,就默认取到最后一个并且包含最后一个 print(name[0:6]) print(name[:6]) print(name[0:3]) print(name[0:3][0:2]) print(name[0:3][0:2][1]) print("====") print(name[0:3][0:2][1][1]) print("===") name2 = list(["warrior", "fury"]) print(name2[0:1]) # print(name2[0:1][1]) #切分到只有两个元素后,就不要再进行切分啦,直接利用下标进行引用 print(name2[0][1]) print("===start===") print(name2) print("===one===") name2[1] = "peter" #修改元素的值 print(name2) print("===two===") name2.insert(0,"bob") #插入一个元素到列表中 print(name2) print("===three===") name2.append("hello") #追加一个元素到最后 print(name2) print("===four===") name2.remove("bob") #删除一个元素 print(name2)
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ name = ["fury",'warrior',1234,3,234,3,1,234,23,3,"bob","fury"] if "fury" in name: #判断"fury" 是否在列表name中 num_of_ele = name.count("fury") #算出"fury"在列表中的个数 positionOfEle = name.index("fury") #找到第一个"fury"的位置 print("[%d] "fury" is in the list of name and the first position is [%d]." %(num_of_ele, positionOfEle)) print(name[positionOfEle]) name[positionOfEle] = "peter" #修改元素的值 print(name[positionOfEle]) print("===one===") #怎么改变一个列表中所有的相同元素 name1 = list([1,2,3,4,4,2,1,2,1,2,1,1,1]) print(name1) #同时改变相同元素的值 if 1 in name1: numOf1 = name1.count(1) print("%d 1 is in the list of name1." %(numOf1)) for i in range(numOf1): posOf1 = name1.index(1) name1[posOf1] = "33" print(name1) print(1 in name1)
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ """ 作业要求: 写一个列表,列表包含本组所有成员 往中间插入两个临组成员的名字 取出两个临组成员 删除第12个人 把刚才加入的那2个其它组的人一次性删除 把组长的名字加上组长备注 每隔一个人打印一个人 """ name2 = [5, 6, 7, 8] name1 = [1, 2, 3, 4] name3 = [9, 10, 11, 12] print("===start===") for i in range(8): if i < 4 : name2.insert(2 + i, name1[i]) else: name2.insert(2 + i, name3[-(8 - i)]) print(name2) print("===one===") name4 = name2[2:10] # 切片处理 print(name4) print("===two===") name2.remove(8) #删除一个元素 print(name2) print("===three===") del name2[2:10] # del 是全局的,什么都可以删 #删除多个元素 print(name2) print("===four===") name2[0] = "组长" #改变元素的值 print(name2) print("===five===") print(name2[0::2]) #间隔打印列表的元素 print("===six===") x = 123 print(x) del x # print(x) #经过del删除后变量x就不存在啦
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ # 经一个列表整体加载到另一个列表的后面 print("===start===") name1 = [1,2,3,12,321,32,21] name2 = [3,4,5] print(name1) name1.extend(name2) print(name1) print(name2) print("===one===") # 将一个列表进行反转处理 name2.reverse() print(name2) # 排序:在3.5中不同的数据类型不能够混合排序 name1.sort() print(name1)
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ import copy # 利用pop删除元素 print("===start===") name = ["fury","warrior","peter","bob"] print(name) name.pop() #默认删除最后一个 print(name) name.pop(1) #参数是元素的位置 print(name) # copy方法_1 print("===one===") name1 = ["fury","warrior","hello"] name2 = name1.copy() name1[0] = "FURY" print(name1) print(name2) # copy_2 : copy没有办法copy第二层,即如果列表中有一个元素是列表类型,那么copy过来的是 # 这个列表的地址,而不是这个列表中真正的值,所以会形成一改全改的结果 print("===two===") lis1 = ["fury","warrior",[1,2,3]] lis2 = lis1.copy() print(lis1) print(lis2) lis1[2][0] = "hello" print(lis1) print(lis2) lis2[2][1] = "world" print(lis1) print(lis2) #解决办法利用copy库 print("===three===") lis3 = lis1.copy() print(lis3) # print("浅copy") # lis3 = copy.copy(lis1) # lis1[2][2] = "NeverCtrl_C" # print(lis3) print("深copy") lis3 = copy.deepcopy(lis1) lis1[2][2] = "NeverCtrl_C" print(lis3)
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ # 找出所有的9并且改成999 # 找出所有的34并且直接删掉 lis = [9,1,34,2,9,23,34,9,9,34] print(lis.count(9)) print(lis.count(34)) print(lis) print("长度为:%d" %len(lis)) for i in range(lis.count(9)): lis[lis.index(9)] = 999 print(lis) for i in range(lis.count(34)): lis.remove(lis[lis.index(34)]) print(lis) print("长度为:%d" %len(lis))
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ list = ["fury","warrior","peter"] print("===one===") for item in enumerate(list): print(item) # enumerate() 是一个枚举,它返回的是一个元组,元组的第一个元素是 # 从0开始的下标,元组的第二个元素是内容
# Keep Calm and Carry on # _*_coding:utf-8_*_ # Author: NeverCtrl_C """ """ lis01 = [1,[1,2,"warrior"],("warrior",132),3,"fury"] print("