1.安装python一定要配置环境变量,python分为2.x,3.x,一般用2.x

2.对python而言可以使用pycharm2.7作为图形化界面工具

3.使用input()函数,注意在键盘输入的时候字符串一定要带""号返回可以是数字或者字符串,#字符串带引号,否则会报错
print "Who do you think I am?"
input()
print "Oh,yes!"
----------------
Who do you think I a"jjks"                           //注意输入的时候输入带引号字符或者不带引号的数字?
串要带双引号(英文格式的)
Oh,yes!

4.使用raw_input()函数,注意在键盘输入的时候字符串不需要带引号,返回的是字符串类型
print "Who do you think I am?"
raw_input()
print "Oh,yes!"
--------------------------------
Who do you think I am?
sdfas
Oh,yes!

5.If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+), this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file.

#coding=utf-8         //声明编码格式,这里不是注释,若不注明,则print 后面接中文会报错,第一行或第二行都可以
# _*_coding:utf-8_*_  //用这个声明也可以,防止代码中出现中文字符后报错
print  "请输入:"
raw_input()
print  "binggo!"

6.在pycharm中显示行号,点击才当图标中的“扳手”---appearance---show line numbers勾选就行
解决pycharm中文乱码问题,方案为首先在代码的开头输入# _*_coding:utf-8_*_,如果编译的时候不行那么可以依次打开File---settings--Editor--File Encodings,然后将里面的IDE encoding与project encoding都改为utf-8编码格式就可以了

7.python 常见的变量
  a.bool(布尔)
  b.整数
  c.浮点数---小数
  d.字符串--需要用" 或"" 符号引起来

8.pycharm 常用快捷键
  Ctrl+/选中行后批量添加注释
  Shift+Enter  开始新行
  Ctrl+Shift+j  合并行
  Ctrl+Delete 刪除到字符結尾
  Ctrl+Backspace 刪除到字符开始
  Tab 缩进
  shift+Tab 反向缩进
  alt+鼠标拖动可以选中多行空白行,然后删除
  ctrl+D鼠标在任意位置复制当前行
  ctrl+Y删除当前行

9. 常用的逻辑运算符
  >;<;>=;<=;==;!=(不等于),not(非);and(与);or(或)
10.选择某一条来执行用到的语句(if)内部用4空格或1tab代替java中{}
 if----true(做点啥)---false(跳出直接进行下一步)
 语法为
 if 条件:
  选择执行的语句

11. 循环体 while
        while----true(循环体)---false(跳出循环体)
 语法为
 while 条件:
  循环执行的语句
  while a != 0:
    print "please input"
     a = input("坑爹:")
  print "over"
-----------------------
please input
坑爹:1
please input
坑爹:2
please input
坑爹:3
please input
坑爹:
------------------------------------------------
12. #coding = utf-8                声明编码方式
     #__author__ = 'Administrator'
from random import randint      #从random模块中引入 randint的方法(随机数)
num = randint(1, 100)             #逗号后面要有空格,等号左右两边也要有空格
print "guess what I think?"
bingo = False
while bingo == False:    #一定是条件为true才会执行循环体(这个是真)
    answer = int(raw_input())      #这里用了强制转换的概念
    if answer < num:
        print "too small!"
    if answer > num:
        print "too big!"
    if answer ==num:
        print "bingo!"
        bingo=True
-------------------------------------------------------------------------------------
13.变量命名的规则
 a)第一个字符必须是字母或者下划线“_”
 b)剩下的部分可以是字母、下划线“_”或数字(0-9)
 c)变量名称是对大小写敏感,myname和myName不是一个变量。

14.求1-100的和(5050)
#coding=utf-8
#__author__ = 'Administrator'
num = 0
i = 0
while i <= 100:
    num += i
    i += 1
print num

或者
#coding=utf-8
#__author__ = 'Administrator'
num = 0
for i in range(1, 101):     #“,”后面要有空格
    num += i
print  num
----------------------------------------------
15.
a = True           
b = not a
print b
print not b
print a == b
print a != b
print a and b
print a or b
print 1 < 2 and b == True

结果:
False True False True False True False
-------------------
16. for 循环 
格式:for 变量名 in range(a, b+1)  #(从a循环到b)  b+1>例如:for i in range(0, 101)包含零不包含101的和,也就是1-100所有整数的和
range()函数的用法range(start,end[,step])----中括号括起来的可以省略参数
>>> range(1,5) #代表从1到5(不包含5)
[1, 2, 3, 4]
>>> range(1,5,2) #代表从1到5,间隔2(不包含5)
[1, 3]
>>> range(5) #代表从0到5(不包含5)
[0, 1, 2, 3, 4]
#for i in I   ---I除了表示range函数可以是集合,当I为集合时,for循环表示遍历I集合中的每个元素,当I为字符串时,for循环表示遍历字符串每个元素
---------------------
17.字符串,强调一定得是英文字符的,一般字符串表示的格式有以下几种,一种直接用双引号隔开,一种是用单引号隔开,print打印效果一样的,还有一种是'''内容'''
或者"""内容"""表示
print "hello"
print "jj"
print 'dd'
print """ jjj 'what'"""
print ''' jkk'ss '''
dd = '33'  # 变量
print dd

结果:
hello
jj
dd
 jjj 'what'
 jkk'ss
33

-----------
18.\的用法
1)引号的话还有一种表示引号的方法,就是\'表示单引号,\"表示双引号,\\表示\,\n表示换行
2)就是在代码中换行后,而不影响输出的结果
# _*_coding:utf-8_*_
# __author__ = '10459'
print "ddd\
dddd\'\""

结果:
ddddddd'"
----------------------------------------------
19.
# _*_coding:utf-8_*_
# __author__ = '10459'
print "He said,\"I\'m yours!\""
print """He said,"I'm yours!\""""
print "\\\\_v_//"
print "Stay hungry,\nstay foolish.\n- Steve Jobs"
print "*\n***\n*****\n***\n*"

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
He said,"I'm yours!"
He said,"I'm yours!"
\\_v_//
Stay hungry,
stay foolish.
- Steve Jobs
*
***
*****
***
*

Process finished with exit code 0
--------------------------------------------------------
20.字符串的格式化
1)函数   str(x) ----- 把x转换成字符串
    int(x)----把x转换成整数
    float(x)---把x转换成字符串
    bool(x)--把x转换成bool值
2)%d --代表需替代的整数  
   %f --代表需替代的小数  %.3f代表保留3位小数
   %s --代表需替代的字符串
   要替代的值如%12  %'s4' %3.23 %str4 %"dd"
   #注意区分:有引号的表示一段字符,没有引号的就是一个变量,这个变量可能是字符,也可能是数字,但一定要和%所表示的格式相一致
3)一句话中有多个要替代的格式如下:print "%s %d %f" %('def', 23, 3.4)  ---括号中这中表示格式在python中被称作元组
   #无论有多少个值需要代入字符串中进行格式化,只需要在字符串中的合适位置用对应的%表示,然后在后面的括号中按顺序提供代入的值就可以了。占位的%和括号中的值在数量上必须相等,类型也要匹配
# _*_coding:utf-8_*_
# __author__ = '10459'
str1 = 'good'
str2 = 'bye'
str4 = 'my'
print str1 + 'and' + str2
str3 = 18
print str2 + str(str3)
print str2 + str(18)
print "my age is %d" % str3
num = input()
print "my age is %d" % num
print "my age is %d" % 19
print "my age is %.2f" % str3
print "my age is %f" % 3.678
print "my age is %.2f" % 4.5555
print "%s age is 18" % "my"
print "%s age is 18" % str4
print "%s age is 18" % str(4)
print "%s age is %d " % (str4, 18)
print "%s %s %s %d" % (str4, 'age', "is", 19)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
goodandbye
bye18
bye18
my age is 18
76
my age is 76
my age is 19
my age is 18.00
my age is 3.678000
my age is 4.56
my age is 18
my age is 18
4 age is 18
my age is 18
my age is 19

Process finished with exit code 0
---------------------------------------------------------------
21.输出的用法
#print 表示换一行,print "\n",也表示换一行
print "\n" 运行结果为空两行
#注意在python中输出大家都知道用print 'dd'但是这里要注意就是这里运行完了会换一行
#要想不换行的话那么就应该这种格式:print "ddd", 这个逗号起不还行的作用,但是这里虽然不换行,不过还是会空一格
# _*_coding:utf-8_*_
# __author__ = '10459'
print
print "dd",
print 'rr'
print 'dd'

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"

dd rr
dd
-------------------------------------
22.for 循环,格式如下:
 for i in range(1, 10) ---表示i从1取到9
1)范例1(乘法口诀)
# _*_coding:utf-8_*_
# __author__ = '10459'
for i in range(1, 10):        #这个小循环看完之后再看,表明第i行
    for j in range(1, i+1):   #从最里面循环开始表明第i行写的内容,最先看这里便于理解
        print "%d * %d %s %d" % (i, j, "=", i*j),
    print

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81

2)范例2
# _*_coding:utf-8_*_
# __author__ = '10459'
i = input()
j = input

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
3
4
3.000 * 4.000 = 12.000

Process finished with exit code 0
-----------------------------------------------------------------------------
23.bool类型转换
1)在python中,以下数值会被认为是False:
 a.为零的数字,包括bool(0),bool(0.0)
 b.空字符串包括bool(""),bool('')
 c.空集合,包括bool(),bool(()),bool([]),bool({})
 d.值为None bool(None)
 e.其他的都为True
2)有一点要注意就是a==bool(0)这个就是个True,a = bool(' ') 这个也是个True因为里面有个空格
3)bool 类型在条件判断用的多,比如a="dd"  i# _*_coding:utf-8_*_
# __author__ = '10459'
a = bool(-123)
print a
a == bool(0)
print a
a = bool(0)      #false
print a
a = bool('abc')
print a
a = bool('False')
print a
a = bool('')    #false
print a

a = bool(0.0)
b = bool()
c = bool({})
d = bool([])
e = bool(None)
f = bool("")
g = bool('')
h = bool(0)
i = bool(())
l = bool(' ')    # 空格True

print a, b, c, d, e, f, g, h, i, l

a = "123"
b = "False"
if a:
    print "this is not a blank String"
if bool(a):
    print "this is not a blank string again"
if b != '':
    print "this is not a blank string three times"f bool(a): print "hhkk"

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
True
True
False
True
True
False
False False False False False False False False False True
this is not a blank String
this is not a blank string again
this is not a blank string three times

Process finished with exit code 0
----------------------------------------------------------------
24.python中函数的定义:(无参数)
 格式如下举例:
 def sayHello():
  print "hello world"
 解析:def 是定义函数的关键字;sayHello为函数的名字,背后一个():里面没有参数;
 print里面就是函数里面的内容了
 python定义函数的时候前面要空两行比较合理,然后函数名字英文拼音要正确,引用的时候一定要在定义函数之后引用,而不像java一样在前引用
# _*_coding:utf-8_*_
# __author__ = '10459'

def goodbye():
    a = "123"
    b = "False"
    if a:
        print 'this is not a blank String'
    if bool(a):
        print "this is not a blank string again"
    if b != '':
        print "this is not a blank string three times"

goodbye()   #引用函数

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
this is not a blank String
this is not a blank string again
this is not a blank string three times

Process finished with exit code 0
------------------------------------------------------------------------
25.dos窗口常用命令
dir ----查看文件类型详情
more--查看文件的文本内容,如txt,py,java,c格式等等
D:-----进入D盘
cd: --- 进入当前盘的某个路径   cd.进入当前目录,cd..返回上一层目录
--------------------------------------------------------------------------
26.定义有参数的函数
格式如下:
 def plus(num1,num2)
  print num1+num2
函数的值相当于一个变量而这个变量的值是在调用函数的时候被赋予的。调用函数的时候,同样把需要传入的参数值放入括号中,用逗号隔开,要注意提供参数值的数量和类型与函数定义中保持一致,所以当函数不是自己写的时候,需要了解函数参数的数量和类型能顺利的调用它。
# _*_coding:utf-8_*_
# __author__ = '10459'

def plus(num1, num2):
    print num1+num2

x = 2
y = 3
plus(x, y)

x = "sss"
y = "yyy"
plus(x, y)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
5
sssyyy

Process finished with exit code 0

---------------------------------------------------------------------------
27.定义函数中,return的用法
return是函数的结束语句,return后面的值被称为这个函数的返回值,函数中任何地方return被执行的时候,这个函数就会结束。
调用函数的时候,函数可以把某个功能的代码分离出来,在需要的时候可以重复使用。在很多时候都是把函数进行封装
# _*_coding:utf-8_*_
# __author__ = '10459'
from random import randint

def isequal(num1,num2):
    if num1 < num2:
        print "too small"
        return False
    if num1 > num2:
        print "too big"
        return False
    if num1 == num2:
        print "bingo"
        return True

num = randint(1,100)      #生成随机数范围为[1,100]
print "Guess what I think?"
bingo = False
while bingo == bool(bingo):
    answer = input()
    bingo = isequal(answer, num)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
Guess what I think?
34
too small
67
too small
91
too big
90
too big
87
too big
84
too big
79
bingo
-------------------------------------------------------------
28. if /if...else / if ---elif---else 逻辑判断语法解析(判断的时候需要用的是逻辑符号如>,<,==,!=等等)
if :表示条件满足,就做点啥,否则就不做
if--else:表明如果条件满足就执行一件事,而条件不满足则用else执行另一件事,与if有差别
          if--else的特殊用法就是可以嵌套。
if else 可以用in
举例:
hi = "hello world"
if "hello" in hi:
    print "contain"
else:
    print "not contain"

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
contain

Process finished with exit code 0

if--elif--else:表明如果满足条件1,则作1相关的事情,否则如果满足条件2,则用elif作2相关的事情,以此类推,如果都不满足,则用else跳出,执行最后的事情。
范例:
if的用法在编号27标题中已经在函数引用中列明,所以这里不再赘述。
1)#if--elif--else的用法:
# _*_coding:utf-8_*_
# __author__ = '10459'
from random import randint

def isequal(num1, num2):
    if num1 < num2:
        print "too small"
        return False
    elif num1 > num2:
        print "too big"
        return False
    else:
        print "bingo"
        return True

num = randint(1,100)      #生成随机数范围为[1,100]
print "Guess what I think?"
bingo = False
while bingo == bool(bingo):
    answer = input()
    bingo = isequal(answer, num)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
Guess what I think?
333
too big
67
too big
45
too big
34
too big
23
too big
12
too small
15
too small
18
too small
21
too big
20
bingo

2)#if--else的用法
# _*_coding:utf-8_*_
# __author__ = '10459'
print "开始输入:",        #加逗号的意思是可以不换行直接在冒号后面输入
a = input()
if a == 1:
    print "right"
else:
    print "wrong"

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
开始输入: 34
wrong

Process finished with exit code 0

3)if---else的嵌套,用比较笨的方法写出的三角形判断
# _*_coding:utf-8_*_
# __author__ = '10459'

def triangle(a, b, c):
    if(a+b>c and b+c>a and a+c>b):    # 一般三角形
        if(a == b and b != c or b == c and b != a or a == c and a != b):  # 等腰三角形
            if(a == b and b == c):  # 等边三角形
                print "a,b,c三边长可以构成等边三角形"
            else:
                print "a,b,c三边长可以构成等腰三角形"

else:
            print "a,b,c三边长可以组成一般三角形"

else:
        print"a,b,c三边长不能组成三角形"

print "请输入三角形边长a的值:",
a = input()
print "请输入三角形边长b的值:",
b = input()
print "请输入三角形边长c的值:",
c = input()
triangle(a, b, c)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
请输入三角形边长a的值: 2
请输入三角形边长b的值: 4
请输入三角形边长c的值: 6
a,b,c三边长不能组成三角形

Process finished with exit code 0
---------------------------------------
if--else实例2
# _*_coding:utf-8_*_
# __author__ = '10459'
print "请输入数字a=",
a = input()
print "请输入数字b=",
b = input()

def xiangxian(x, y):
    if x >= 0:
        if y >= 0:
            print "此坐标为第一象限"
        else:
            print "此坐标为第四象限"
    else:
        if y >= 0:
            print "此坐标为第二象限"
        else:
            print "此坐标为第三象限"
xiangxian(a, b)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
请输入数字a= 4
请输入数字b= 4
此坐标为第一象限

Process finished with exit code 0

-----------------------------------------------------------------------------------------
29.python中数组叫做list,用来处理一组有序项目的数据结构,如I = [1, 2, 3, 4, 5, 6, 7, 8, 9] ,这就是一个list
list 除了 是数字外还可以别的类型,比如I = ["mat", "ade", "rice", "milk"]
还可以是不同类型的混合,比如I = [123, "skk", 0.888, True, 'sss']
空list的多种创建方法1)a = [],或者 a = list()
# _*_coding:utf-8_*_
# __author__ = '10459'
print range(1, 10)    #可以用for i in range(1,10)循环来遍历它,m = range(1, 10),则可改成for i in m

结果:(就是一个list)
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Process finished with exit code 0
----------------------------------------------------------------------------------------
30.操作list
1)访问list中的元素
如:I = [123, "everyday", 'kkks', True, 0.876]
访问的话可以直接打印,list里面元素编号是从0开始的
比如上面五个元素,可直接打印:
# _*_coding:utf-8_*_
# __author__ = '10459'
I = [123, "everyday", 'kkks', True, 0.876]
print I[0], I[1], I[2], I[3], I[4]
for i in I:
    print i,
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
123 everyday kkks True 0.876
123 everyday kkks True 0.876

Process finished with exit code 0
2)修改list中的元素,只需要给里面的元素赋值就可以了
# _*_coding:utf-8_*_
# __author__ = '10459'
I = [123, "everyday", 'kkks', True, 0.876]
print I[0], I[1], I[2], I[3], I[4]
for i in I:
    print i,
print
I[0] = "ddd"
I[2] = 123
print I

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
123 everyday kkks True 0.876
123 everyday kkks True 0.876
['ddd', 'everyday', 123, True, 0.876]

Process finished with exit code 0
3)在list中添加元素,可以用I.append(元素值)
 删除list中的元素,可以用del I[元素编号]
# _*_coding:utf-8_*_
# __author__ = '10459'
I = [123, "everyday", 'kkks', True, 0.876]
I[0] = "ddd"
I[2] = 123
print I
I.append("sss")
print I
del I[0]
print I

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
['ddd', 'everyday', 123, True, 0.876]
['ddd', 'everyday', 123, True, 0.876, 'sss']
['everyday', 123, True, 0.876, 'sss']

Process finished with exit code 0
---------------------------------------------------------------------------------------------------
31.点球游戏
# _*_coding:utf-8_*_
# __author__ = '10459'
from random import choice
print "Choose one side to shoot"
print "left,center,right"
you = raw_input()
print "You kicked:" + you
direction = ['left', 'centre', 'right']
com = choice(direction)   # 表示从list中随便挑选一个元素
print 'Computer saved:' + com
if you != com:
    print "Goal!"
else:
    print 'Oops...'
---------------------------------------------------------------
32.#list 的索引
1)用[]加序号访问的方法就是索引的一种方法--指定位置索引如I[2]表示I集合中第三个元素
2)可以处理负数的索引。如I[-1]表示I中最后一个元素,I[-3]表示I中倒数第三个元素
   #list 的切片
切片操作符格式:[切片的开始位置:切片的结束位置],切片时,开始位置包含在切片中,结束位置不包括,如I[1:-1] ---表示为I中第2位到倒数第一位,不包含倒数第一位。
# _*_coding:utf-8_*_
# __author__ = '10459'
I = ["123", "every day", "大", 0.444, True]      #为了防止打印list的时候中文乱码问题,需先转换成字符串,然后用sting类里面的decode方法
print '%s' % str(I[0:4]).decode('string_escape')
for i in I:                              
    print i
I[2]='小'
print I[-3]
print '%s' % str(I[1:-4]).decode('string_escape')   #这里第一个和最后一个指向同一个元素,以不包含这个元素的优先级高这里输出[],I[1:-5]也是输出空白
print '%s' % str(I[1:-3]).decode('string_escape')  
print '%s' % str(I[1:-1]).decode('string_escape')
print '%s' % str(I[1:]).decode('string_escape')
print '%s' % str(I[:-1]).decode('string_escape')

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
['123', 'every day', '大', 0.444]
123
every day

0.444
True

[]
['every day']
['every day', '小', 0.444]
['every day', '小', 0.444, True]
['123', 'every day', '小', 0.444]

Process finished with exit code 0
-------------------------------------------------
33.点球游戏,记分
# _*_coding:utf-8_*_
# __author__ = '10459'
from random import choice

score_you = 0
score_com = 0
direction = ["left", "center", "right"]

for i in range(5):
    print '====Round %d -YOU Kick!====' % (i+1)
    print 'Choose one side to shoot:'
    print 'left,center,right'
    you = raw_input()
    print "YOU Kicked:" + you
    com = choice(direction)
    print 'Computer saved' + com
    if you != com:
        print "球进了"
        score_you += 1
    else:
        print "球没进"
    print "Score:%d(you) - %d(computer)\n" %(score_you, score_com)

print '====Round %d -YOU Save!====' % (i+1)
    print 'Choose one side to Save:'
    print 'left,center,right'
    you = raw_input()
    print "YOU Saved:" + you
    com = choice(direction)
    print 'Computer Kicked' + com
    if you == com:
        print "球防住了"
    else:
        print "球丢了,电脑得分"
        score_com += 1
    print "Score:%d(you) - %d(computer)\n" %(score_you, score_com)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
====Round 1 -YOU Kick!====
Choose one side to shoot:
left,center,right
left
YOU Kicked:left
Computer savedright
球进了
Score:1(you) - 0(computer)

====Round 1 -YOU Save!====
Choose one side to Save:
left,center,right
center
YOU Saved:center
Computer Kickedright
球丢了,电脑得分
Score:1(you) - 1(computer)

====Round 2 -YOU Kick!====
Choose one side to shoot:
left,center,right
center
YOU Kicked:center
Computer savedright
球进了
Score:2(you) - 1(computer)

====Round 2 -YOU Save!====
Choose one side to Save:
left,center,right
left
YOU Saved:left
Computer Kickedleft
球防住了
Score:2(you) - 1(computer)

====Round 3 -YOU Kick!====
Choose one side to shoot:
left,center,right
right
YOU Kicked:right
Computer savedright
球没进
Score:2(you) - 1(computer)

====Round 3 -YOU Save!====
Choose one side to Save:
left,center,right
left
YOU Saved:left
Computer Kickedleft
球防住了
Score:2(you) - 1(computer)

====Round 4 -YOU Kick!====
Choose one side to shoot:
left,center,right
right
YOU Kicked:right
Computer savedright
球没进
Score:2(you) - 1(computer)

====Round 4 -YOU Save!====
Choose one side to Save:
left,center,right
center
YOU Saved:center
Computer Kickedleft
球丢了,电脑得分
Score:2(you) - 2(computer)

====Round 5 -YOU Kick!====
Choose one side to shoot:
left,center,right
left
YOU Kicked:left
Computer savedcenter
球进了
Score:3(you) - 2(computer)

====Round 5 -YOU Save!====
Choose one side to Save:
left,center,right
center
YOU Saved:center
Computer Kickedcenter
球防住了
Score:3(you) - 2(computer)

Process finished with exit code 0
----------------------------------------------------
34.字符串的分割
要抓取网页的链接,那就要对网页的代码进行处理,处理过程中,免不了要在字符串和list之间进行很多操作,那就要对#字符串进行分割。
比如拿到一个句子,sentence = 'I am an English sentence'
sentence.split(),默认是按照空白字符进行分割。当然也可以按照换行符(\n),制表符(\t)分割当然也可以指定分割符号。
# _*_coding:utf-8_*_
# __author__ = '10459'

sentence = "I am an Englist sentence"
P = sentence.split()
I = sentence.split('a')
print I, P
section = 'Hi. I am the one.Bye.'
print section.split('.')
print 'aaaa'.split('a')

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
['I ', 'm ', 'n Englist sentence'] ['I', 'am', 'an', 'Englist', 'sentence']
['Hi', ' I am the one', 'Bye', '']
['', '', '', '', '']

Process finished with exit code 0
---------------------------------------------------------------------------------
35.点球小游戏加上胜负判断
# _*_coding:utf-8_*_
# __author__ = '10459'
from random import choice

score = [0, 0]
direction = ["left", "center", "right"]

def kick():
    print "==== You Kick!===="
    print 'Choose one side to shoot:'
    print 'left,center,right'
    you = raw_input()
    print "You kicked" + you
    com = choice(direction)
    print "Computer saved" + com
    if you != com:
        print "恭喜!球进了!"
        score[0] += 1
    else:
        print "很遗憾!球没进"
    print 'Score: %d(you) - %d(com)\n' % (score[0], score[1])

print "====You Save!===="
    print 'Choose one side to save:'
    print 'left, center, right'
    you = raw_input()
    print "You Saved" + you
    com = choice(direction)
    print 'Computer kicked' + com
    if you == com:
        print "恭喜球,防住了"
    else:
        print "很遗憾,球丢了"
        score[1] += 1
    print 'Score:%d(you) - %d(com)\n' % (score[0], score[1])

for i in range(5):
    print '=====Round %d ====' %(i+1)
    kick()

while score[0] == score[1]:
    i += 1
    print '==== Round %d ====' %(i+1)
    kick()
if score[0] > score[1]:
    print "you win!"
else:
    print "you lose!"

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Max.py"
=====Round 1 ====
==== You Kick!====
Choose one side to shoot:
left,center,right
left
You kickedleft
Computer savedright
恭喜!球进了!
Score: 1(you) - 0(com)

====You Save!====
Choose one side to save:
left, center, right
center
You Savedcenter
Computer kickedcenter
恭喜球,防住了
Score:1(you) - 0(com)

=====Round 2 ====
==== You Kick!====
Choose one side to shoot:
left,center,right
center
You kickedcenter
Computer savedleft
恭喜!球进了!
Score: 2(you) - 0(com)

====You Save!====
Choose one side to save:
left, center, right
left
You Savedleft
Computer kickedright
很遗憾,球丢了
Score:2(you) - 1(com)

=====Round 3 ====
==== You Kick!====
Choose one side to shoot:
left,center,right
left
You kickedleft
Computer savedcenter
恭喜!球进了!
Score: 3(you) - 1(com)

====You Save!====
Choose one side to save:
left, center, right
right
You Savedright
Computer kickedcenter
很遗憾,球丢了
Score:3(you) - 2(com)

=====Round 4 ====
==== You Kick!====
Choose one side to shoot:
left,center,right
left
You kickedleft
Computer savedright
恭喜!球进了!
Score: 4(you) - 2(com)

====You Save!====
Choose one side to save:
left, center, right
center
You Savedcenter
Computer kickedright
很遗憾,球丢了
Score:4(you) - 3(com)

=====Round 5 ====
==== You Kick!====
Choose one side to shoot:
left,center,right
center
You kickedcenter
Computer savedleft
恭喜!球进了!
Score: 5(you) - 3(com)

====You Save!====
Choose one side to save:
left, center, right
center
You Savedcenter
Computer kickedleft
很遗憾,球丢了
Score:5(you) - 4(com)

you win!

Process finished with exit code 0
-----------------------------------------------------------
36.连接list---字符串连接用join。join的方法是字符串的方法而不是list的方法。首先你需要有个字符串作为list中所有元素的连接符,然后再用这个连接符的join方法,join的参数是被连接的list。
# _*_coding:utf-8_*_
# __author__ = '10459'

s = ';'
li = ['apple', 'pear', 'orange', '字符']
fruit = s.join(li)
print f
print ';'.join(li)
print ';'.join(['apple', 'pear', 'orange', '字符'])
print ''.join(['apple', 'pear', 'orange', '字符'])

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
apple;pear;orange;字符
apple;pear;orange;字符
apple;pear;orange;字符
applepearorange字符

Process finished with exit code 0
---------------------------------------------------------------------
37.字符串与list相似与不同
a.可以进行for ... in   遍历,与list相同
b.可以进行加[]索引访问,不同的是字符串不能去更改其中的字符,比如aa = 'ssss' aa[1] = '3'不支持这样赋值
c.通过两个参数,截取一段子串,与list规则相同
d.join对字符串有用,join还可以用连接符把字符串中的每个字符连接成一个新的字符串,不过在实际使用中这种用法比较少

# _*_coding:utf-8_*_
# __author__ = '10459'

aa = u'ssssdd大f'  ---字符串有中文时候,前面加个u就可以遍历或者切片了,注意。
li = ['apple', 'pear', 'orange', '字符']

for i in aa:
    print i
for i in li:
    print i
print aa[6]
print li[0]
print aa[1: 4]
# print '%s' % str(aa[:]).decode('string_escape') ----字符串含中文这样操作会报错,而list这样操作是可以的
print aa[:]
print aa[:-3]
print aa[1: -3]
print aa[1:]
print li[0: 3]
print li[1: -1]
print '%s' % str(li[:]).decode('string_escape')
print li[:-3]
print '%s' % str(li[1:]).decode('string_escape')
print ';'.join(aa)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
s
s
s
s
d
d

f
apple
pear
orange
字符

apple
sss
ssssdd大f
ssssd
sssd
sssdd大f
['apple', 'pear', 'orange']
['pear', 'orange']
['apple', 'pear', 'orange', '字符']
['apple']
['pear', 'orange', '字符']
s;s;s;s;d;d;大;f

Process finished with exit code 0
--------------------------------------------------------------------------------------
38.读文件(以只读方式打开,文件必须存在,否则会引发异常,而写文件则不一定要存在,不存在会自动创建文件)
在保存代码文件夹下放入一个新建的文本文件,比如sss.txt文件,里面随便写几个字母,然后就可以用file('sss.txt'),然后read()它,最后close()(养成好习惯,打开了之后关闭,不然可能会遇到错误)就可以了
# _*_coding:utf-8_*_
# __author__ = '10459'

f = file('sss.txt')
data = f.read()
print data
f.close()

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
hehekljaljdkf
sfldfkdsf
jdksfld
djflksf
sflkdjfls'
大人

Process finished with exit code 0
-----------------------------------------------------------
39.readline与readlines与read()
readline()  #读取一行内容光标指哪里就读哪行,读完后自动切换到下一行,string格式
readlines() #读取文件所有内容,然后按行读取至一个list中,按行分开。list
read() #读整个文件的内容至一个string里
---
# _*_coding:utf-8_*_
# __author__ = '10459'

f = open('score.txt', 'r')
# a = f.read().decode('gbk')
b1 = f.readline().decode('gbk')  #字符串转码用decode函数里面加个'gbk'
b2 = f.readline().decode('gbk')
b3 = f.readline().decode('gbk')
b4 = f.readline().decode('gbk')
b5 = f.readline().decode('gbk')
# print a
print b1
print b2
print b3
print b4
print b5
# c = f.readlines()
# print c
f.close
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
中一 77 89 89 90 100

中而 56 90 99 10 45 78

看到 87 90 99 99

得到 90 45

诸葛两 99 88 33

Process finished with exit code 0
---
# _*_coding:utf-8_*_
# __author__ = '10459'

f = open('score.txt', 'r')
c = f.readlines()
print c
f.close

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
['\xd6\xd0\xd2\xbb 77 89 89 90 100\n', '\xd6\xd0\xb6\xf8 56 90 99 10 45 78\n', '\xbf\xb4\xb5\xbd 87 90 99 99 \n', '\xb5\xc3\xb5\xbd 90 45\n', '\xd6\xee\xb8\xf0\xc1\xbd 99 88 33']

Process finished with exit code 0
---
# _*_coding:utf-8_*_
# __author__ = '10459'

f = open('score.txt', 'r')
c = f.readlines()
print '\n'.join(c).decode('gbk')
f.close

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
中一 77 89 89 90 100

中而 56 90 99 10 45 78

看到 87 90 99 99

得到 90 45

诸葛两 99 88 33

Process finished with exit code 0

---

# _*_coding:utf-8_*_
# __author__ = '10459'

f = open('score.txt', 'r')
a = f.read().decode('gbk')
print a
f.close
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
中一 77 89 89 90 100
中而 56 90 99 10 45 78
看到 87 90 99 99
得到 90 45
诸葛两 99 88 33

Process finished with exit code 0
---
# _*_coding:utf-8_*_
# __author__ = '10459'

f = open('sss.txt', 'r')
result = list()
for line in open('sss.txt'):
    line = f.readline()
    print line,
    print line
    result.append(line)
print result
f.close()

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
hehekljaljdkf1
hehekljaljdkf1

sfldfkdsf2
sfldfkdsf2

jdksfld3
jdksfld3

djflksf4
djflksf4

sflkdjfls'5
sflkdjfls'5

['hehekljaljdkf1\n', 'sfldfkdsf2\n', 'jdksfld3\n', 'djflksf4\n', "sflkdjfls'5\n"]

Process finished with exit code 0

------注意写文件的时候假如当前目录没有那个文件则会自动创建新文件然后再写------
# _*_coding:utf-8_*_
# __author__ = '10459'

f = open('sss.txt', 'r')                       # 以读方式打开文件(默认也是以只读文件打开假如写模式,则把r改成w就可以)
result = list()
for line in f.readlines():                     # 依次读取每行??
    line = line.strip()                        # 去掉每行头尾空白??
    if not len(line) or line.startswith('#'):  # 判断是否是空行或注释行??
        continue                               # 是的话就继续
    result.append(line)                        # 保存
result.sort()                                  # 排序结果,这里不排序也可以,不排序的话结果会以12345排,下面结果是排序后效果?
print result
open('bbb.txt', 'w').write('%s' % '\n'.join(result))  # 保存入结果文件??

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
['djflksf4', 'hehekljaljdkf1', 'jdksfld3', 'sfldfkdsf2', "sflkdjfls'5"]

Process finished with exit code 0
----------------------------------------------------------------------------------------------
40.写文件有两种模式,一种是'w'(writing),一种是'a' (appending)两者区别在于,w会覆盖原有文件的内容,而a不会覆盖
格式有两种:
1)f = file('data.txt', 'w')
2)f = open('data.txt', 'w')
写入的方法也比较简单
f.write('kskfdlaksd')字符串或者f.write(data)---data为字符串变量
# _*_coding:utf-8_*_
# __author__ = '10459'

data = "I will be in a file.\n So cool!"
out = open('output.txt', 'w')
out.write(data)
out.close()                                # 也可以直接open('output.txt', 'w').write("I will be in a file..")

在文件output.txt里面有
I will be in a file.
 So cool!
在pycharm中无报错提示
# _*_coding:utf-8_*_
# __author__ = '10459'

ddd = raw_input()
sss = open('output1.txt', 'w')
sss.write(ddd)
sss.close()

结果就是:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
dddfdfssdfsd

Process finished with exit code 0
手动输入内容输入的内容保存了一个文件
----------------------------------------------------------
41.处理文件中的数据,以txt文件格式成绩表为例子
1)把文件读进,来
2)取得文件中的数据,因为每一行都是一条学生的成绩记录,所以用readlines,把每一行分开,便于之后的数据处理
3)对每一条数据进行处理,按照空格,把姓名,每次的成绩分割开,之后对于数据的处理用for循环
4)整个程序最核心的部分到了,如何把一个学生的几次成绩进行合并,并保存起来呢?我的做法是,对于每一条的数,都新建一个字符串,把学生的名字和
算好的总成绩保存进去,最后再把这些字符串保存到文件中
5)得到一个学生的总成绩后,把它添加到一个list中
6)全部成绩处理完毕之后,把results中的内容保存至文件。因为results是一个字符串组成的list,这里我们直接用writelines
# _*_coding:utf-8_*_
# __author__ = '10459'

f = file('score.txt')
lines = f.readlines()
print lines
f.close()

results = list()

for line in lines:
    print line.decode('gbk')
    data = line.split()
    print data

sum = 0
    for score in data[1:]:         #切割后遍历score为字符串注意,所以下面要作强制转换
        sum += int(score)
    result = '%s \t: %d\n' % (data[0], sum)
    print result.decode("gbk")

results.append(result)
print results
output = file('result.txt', 'w')
output.writelines(results)
output.close()

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
['\xd6\xd0\xd2\xbb 77 89 89 90 100\n', '\xd6\xd0\xb6\xf8 56 90 99 10 45 78\n', '\xbf\xb4\xb5\xbd 87 90 99 99 \n', '\xb5\xc3\xb5\xbd 90 45\n', '\xd6\xee\xb8\xf0\xc1\xbd 99 88 33']
中一 77 89 89 90 100

['\xd6\xd0\xd2\xbb', '77', '89', '89', '90', '100']
中一  : 445

中而 56 90 99 10 45 78

['\xd6\xd0\xb6\xf8', '56', '90', '99', '10', '45', '78']
中而  : 378

看到 87 90 99 99

['\xbf\xb4\xb5\xbd', '87', '90', '99', '99']
看到  : 375

得到 90 45

['\xb5\xc3\xb5\xbd', '90', '45']
得到  : 135

诸葛两 99 88 33
['\xd6\xee\xb8\xf0\xc1\xbd', '99', '88', '33']
诸葛两  : 220

['\xd6\xd0\xd2\xbb \t: 445\n', '\xd6\xd0\xb6\xf8 \t: 378\n', '\xbf\xb4\xb5\xbd \t: 375\n', '\xb5\xc3\xb5\xbd \t: 135\n', '\xd6\xee\xb8\xf0\xc1\xbd \t: 220\n']

Process finished with exit code 0
------------------------------------------------------------------------------------
42.break与continue的使用
1)当while循环条件不满足时候结束
2)for循环遍历完序列后结束
如果在循环条件仍然满足或序列没有遍历完的时候,想要强行跳出循环,就需要用到break语句,break只能跳出当前所属循环,外面有循环需要
外面break跳出
3)continue是略过本次循环余下的内容,直接进入下一个循环,而不能直接彻底跳出本次循环。
# _*_coding:utf-8_*_
# __author__ = '10459'

for i in range(10):
    a = raw_input()
    if a == 'EOF':
        break
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
skdf
EOF

Process finished with exit code 0
----
# _*_coding:utf-8_*_
# __author__ = '10459'

while True:
    a = raw_input()
    if a == 'EOF':
        break
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
dsf
EOF

Process finished with exit code 0
----
# _*_coding:utf-8_*_
# __author__ = '10459'

f = file('score.txt')
lines = f.readlines()
# print lines
f.close()

results = list()

for line in lines:
    print line.decode('gbk')
    data = line.split()
# print data

ss = 0
    for score in data[1:]:
        point = int(score)
        if point < 60:
            continue               #continue 的用法若有这个条件则跳过本次循环直接进行下次循环
        ss += int(score)
    result = '%s \t: %d\n' % (data[0], ss)
    print result.decode("gbk")

results.append(result)
# print results
output = file('result.txt', 'w')
output.writelines(results)
output.close()

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
中一 77 89 89 90 100

中一  : 445

中而 56 90 99 10 45 78

中而  : 267

看到 87 90 99 99

看到  : 375

得到 90 45

得到  : 90

诸葛两 99 88 33
诸葛两  : 187

Process finished with exit code 0
---
# _*_coding:utf-8_*_
# __author__ = '10459'

i = 0
while i < 5:
    i += 1
    for j in range(3):
        print '%s:%d' % ("j", j)
        if j == 2:
            break
    for k in range(3):
        if k == 2:
            continue
        print '%s:%d' % ("k", k)
    if i > 3:
        break
    print '%s:%d' % ("i", i)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
j:0
j:1
j:2
k:0
k:1    
i:1     #在i的大循环里,先打印完j循环,再打印完k循环,再打印i
j:0
j:1
j:2
k:0
k:1
i:2     #第二次执行完
j:0
j:1
j:2
k:0
k:1
i:3     #第三次执行完
j:0
j:1
j:2
k:0
k:1     #此时i>3跳出循环

Process finished with exit code 0

---------------------------------------------------------------------------------------
43.异常处理
try:
 内容
except:
 内容
表示处理正常的话执行try里面的内容,处理异常的就输出except的内容,也就是说try执行时假如出了问题,就立马
执行except中的语句,假如不使用try---except的话,控制台就输出准确的报错信息
# _*_coding:utf-8_*_
# __author__ = '10459'

print int("0.5")
try:
    print int("0.5")
    print "处理成功"
except:
    print "处理失败"
print "done"
print '7'
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
Traceback (most recent call last):
  File "D:/python-pycharm-installpackage/python script/our test/test1.py", line 4, in <module>
    print int("0.5")
ValueError: invalid literal for int() with base 10: '0.5'

Process finished with exit code 1
#上面报错了。并且之后的语句也不执行
接下来用try--except:
# _*_coding:utf-8_*_
# __author__ = '10459'

# print int("0.5")
try:
    print int("0.5")
    print "处理成功"
except:
    print "处理失败"
print "done"
print '7'

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
处理失败
done
7

Process finished with exit code 0

# 直接把异常报错替换了并且对之后的语句不会影响,代码不会终端,剩下的代码可以正常输出

# _*_coding:utf-8_*_
# __author__ = '10459'

try:
    f = file('ttt.txt')
    print 'file opened!'
except:
    print "file not exists"
print "done"
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
file not exists
done

Process finished with exit code 0
-------------------------------------------------------------------
44.字典(dictionary)用冒号隔开
基本格式是:d = {key1:value1, key2:value2}
其中key1,key2是键,必须唯一只能是简单对象,比如字符串,整数,浮点数,布尔值。比如list不能单独作为键,但是可以作为值。print key1
value1,value2是值,可以相同   print d[key1]
#python 字典中的键/值对没有顺序,我们无法用索引访问字典的某一项,而是要通过键来访问。
# _*_coding:utf-8_*_
# __author__ = '10459'

score = {
    '晓峰': 95, '本本': 77, '大大': 88
}

print score['晓峰']    # 打印对应字典中的名字对应的分数

for name in score:
    print score[name]
score['本本'] = 99     # 更改字典本本的分数
score['笑笑'] = 80     # 增加笑笑的名字和成绩
del score['大大']      # 删除大大的字典(删除键名就可以)
d = {}                 # 创建空字典
for name in score:
    print name, score[name]    # 遍历字典后打印其中的键和值
print d
'''
遍历
#方法1
for key in info:
    print(key,info[key])

#方法2
for k,v in info.items(): #会先把dict转成list,数据里大时莫用
    print(k,v)
'''
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
95
95
77
88
晓峰 95
本本 99
笑笑 80
{}

Process finished with exit code 0
-------------------------------------------------------------------------
45.python自带丰富的标准库,另外还有数量庞大的各种第三方库,使用这些"巨人的"代码,可以让你开发的
效率事半功倍,就像积木一样拼出你的程序,使用这些功能的基本方法就是使用模块。通过函数,可以在程序里
重用代码;通过模块可以重用别的程序中的代码。
模块---模块可以理解为一个包含了函数和标量的py文件,在程序中引入了某个模块,就可以使用其中的函数和变量
1)引入模块的方法:
import 模块名
使用的时候需要模块名+.方法名这样引用一个方法
2)查看模块中有哪些函数和变量,可以用dir(模块名)
3)从模块中引入一个变量或函数可以用
from 模块名  import 函数或变量,类
'''
模块名相当与一个文件名.py格式的,而函数,类变量则相当于在.py格式文件中定义的函数,
类,变量,引用方式直接运行.py文件里的方法变量类神马的。
from import另外一种引用方式是,from 包名 import 模块,相当于从文件夹中导入.py
引用格式是模块.方法名/类/属性等
'''
# _*_coding:utf-8_*_
# __author__ = '10459'

import math      # 引入模块
from math import pi as pai   # 从模块中引入一个变量或函数   as是重新命名

print pai

print dir(math)    # dir函数的用法就是查询函数中包含哪些变量和函数

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
3.14159265359
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

Process finished with exit code 0
------------------------------------------------------------------
46.保存文件小游戏
# _*_coding:utf-8_*_
# __author__ = '10459'
from random import randint

f = open("D:\python-pycharm-installpackage\python script\our test\game play.txt")
score = f.read().split()
f.close()
game_times = int(score[0])  # 总游戏次数
min_times = int(score[1])   # 最快猜出的轮数
total_times = int(score[2])  # 总轮数
if game_times > 0:
    avg_times = float(total_times) / game_times  # 由于可能出现两个整数相除得到一个整数,而且不是四舍五入,所以前面转换成浮点数
else:
    avg_times = 0
print '你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案' % (game_times, min_times, avg_times)
num = randint(1, 100)
times = 0   # 记录每次游戏所用的轮数
print 'Guess what I think?'
bingo = False
while bingo == False:
    times += 1
    answer = input()
    if answer > num:
        print "too big"
    if answer < num:
        print "too small"
    if answer == num:
        print "答对了"
        bingo = True
# 如果第一次玩,或者游戏论数目比最小轮数少则更新最小轮数
if game_times == 0 or times < min_times:
    min_times = times
total_times += times  # 总游戏轮数增加
game_times += 1  # 游戏次数增加
result = '%d %d %d' % (game_times, min_times, total_times)
f = open('D:\python-pycharm-installpackage\python script\our test\game play.txt', 'w')
f.write(result)
f.close()

结果:#初始值一定要是0 0 0,第一次开始玩
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
你已经玩了1次,最少8轮猜出答案,平均8.00轮猜出答案
Guess what I think?
56
too big
33
too big
22
too big
11
too big
9
too big
3
too small
5
too small
7
too small
8
答对了

Process finished with exit code 0
-------------------------------------------------------------
47.保存游戏3
# _*_coding:utf-8_*_
# __author__ = '10459'
from random import randint

name = raw_input('请输入您的中文名字: ')     # 输入玩家的名字

f = open("D:\python-pycharm-installpackage\python script\our test\game play.txt")
lines = f.readlines()
f.close()

scores = {}     # 初始化一个空字典
for l in lines:
    s = l.split()   # 把每一行的数据拆分成一个list
    scores[s[0]] = s[1:]    # list的第一个为key,剩下的为values
score = scores.get(name)    # 查找当前玩家的数据
if score is None:   # 如果玩家没找到
    score = [0, 0, 0]

game_times = int(score[0])  # 总游戏次数
min_times = int(score[1])   # 最快猜出的轮数
total_times = int(score[2])  # 总轮数
if game_times > 0:
    avg_times = float(total_times) / game_times  # 由于可能出现两个整数相除得到一个整数,而且不是四舍五入,所以前面转换成浮点数
else:
    avg_times = 0
print '你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案' % (game_times, min_times, avg_times)
num = randint(1, 100)
times = 0   # 记录每次游戏所用的轮数
print 'Guess what I think?'
bingo = False
while bingo == False:
    times += 1
    answer = input()
    if answer > num:
        print "too big"
    if answer < num:
        print "too small"
    if answer == num:
        print "答对了"
        bingo = True
# 如果第一次玩,或者游戏论数目比最小轮数少则更新最小轮数
if game_times == 0 or times < min_times:
    min_times = times
total_times += times  # 总游戏轮数增加
game_times += 1  # 游戏次数增加

# 把成绩更新到对应玩家的数据中
# 加str转换成字符串,为后面格式化做准备
scores[name] = [str(game_times), str(min_times), str(total_times)]
result = ''  # 初始化一个空字符串
for n in scores:
    # 把成绩按照name game_times min_times total_times 进行格式化
    # 结尾要加上\n换行
    line = n + ' ' + ' '.join(scores[n]) + '\n'
    result += line  # 添加到result中

f = open('D:\python-pycharm-installpackage\python script\our test\game play.txt', 'w')
f.write(result)
f.close()

结果:# 注意这里不会覆盖原来文件中的结果
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
请输入您的中文名字: 大个
你已经玩了0次,最少0轮猜出答案,平均0.00轮猜出答案
Guess what I think?
22
too small
44
too small
66
too small
88
too small
99
too big
95
too big
90
too big
89
答对了
文件里:
大个 1 8 8   #新插入的结果
2 8 17  #之前文本框中有的结果

Process finished with exit code 0
---------------------------------------------
48.函数的默认参数
1)函数只有一个参数的时候,假如定义函数没有默认值,那么引用的时候要把值加上
假如有默认值,则直接引用不加参数,则结果以默认值的形式体现
2)函数有多个参数的时候,假如想给部分参数提供默认参数,那么这些参数必须在函数的末尾,否则
报错
# _*_coding:utf-8_*_
# __author__ = '10459'

def hello(name):    # 定义函数name没有默认值
    print 'hello' + name

def good(name='bye'):   # 定义的函数参数有默认值bye
    print 'good' + name

hello('python') # 没有默认值,则引用函数的时候必须有参数值
good()  # 带有默认参数的,运行的时候可以里面不用写参数名,则结果默认,如果写了,那就用写好的参数
good("morning")

def mm(name='dd', sss='dds'):  # 多个默认参数的引用
    print name + sss
mm()

def ms(name, sss='ssdd'):
    print name + sss
ms("www")
ms("dsd", "ddf")

# def mss(name='dfs', sss):  这样的方式会报错

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
hellopython
goodbye
goodmorning
dddds
wwwssdd
dsdddf

Process finished with exit code 0
---------------------------------------------
49.面向对象
1)面向对象最主要的两个概念:类(class)和对象(object),类是一种抽象的类型,而对象是这
种类型的实例,#举个例子,“笔”作为一个抽象的概念,可以被看成是一个类,而实实在在的一支笔,则是“笔”这种类型的对象。
一个类可以有属于它的函数,这种函数被称为类的“方法”。一个类/对象可以有属于它的变量,这种变
量被称做“域”。域可以分为“类变量”和“实例变量”#如笔的书写功能就是笔这个类的一种方法。每支笔都有自己的颜色,则这种颜色属于某支笔的域,也就是这支笔的实例变量。类变量的话举例子,假设有一种限量版的钢笔,我们为这种笔创建一种类,而这种笔的产量就可以看成这种笔的类变量。因为这个域不属于某一支笔,而是这种类型的笔的共有属性。
2)“域”和“方法”被成为类的属性

# _*_coding:utf-8_*_
# __author__ = '10459'

s = "How are you"   # s被赋值后就是一个字符串类型的对象
l = s.split()       # split 是字符串的方法,这个方法返回一个list类型的对象,l就是一个list类型的对象
print l, s
print type(s), dir(s)  #type打印s对象的类型,dir打印s的所有属性
print type(l), dir(l)

class MyClass:   #定义类的方式
    pass    #pass表示空的代码块

mc = MyClass()      # 新建一个对象mc
print mc           
#打印出来的信息表明mc为__main__模块种MyClass中的一个实例,背后一长串的东西表示这个对象16进制内存地址

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
['How', 'are', 'you'] How are you
<type 'str'> ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
<type 'list'> ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
<__main__.MyClass instance at 0x0000000002D94A88>

Process finished with exit code 0

-------------------------------------------------------------------
50.
1)调用类变量的方法是“对象.变量名”,可以得到它的值,也可以改变它的值
2)调用类方法的写法是“对象.方法名”格式进行调用。#注意,类方法和我们之前定义函数的区别在于,类方法的第一个参数必须是self,而在调用类方法的时候,通过“对象.方法名”调用的时候不需要额外的提供self这个参数的值。self在类方法中的值,就是调用这个对象的本身。
# _*_coding:utf-8_*_
# __author__ = '10459'

class MyClass:
    name = 'sam'        # 定义类变量name,并赋值

def sayhi(self):    # 定义类方法
        print "hello %s" % self.name

mc = MyClass()  #新建类对象
print mc.name  #调用类变量
mc.name = "Lucy" #改变这个对象的类变量值
print mc.name  #再次调用类变量,看看这个对象的变量值有没有变
mc.sayhi()   #调用类方法
dc = MyClass()  #再次创建类对象的时候,调用类变量还是默认值
print dc.name
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
sam
Lucy
hello Lucy
sam

Process finished with exit code 0
-----------------------------------------
51.面象对象举例
假设有一辆汽车,我们知道它的速度(60km/h),又有一辆车速度为150km/h,A,B两地距离100Km,B,C两地距离为200km,算出俩车分别从A,B以及B,C花费的时间。
# _*_coding:utf-8_*_
# __author__ = '10459'

class Car:
    speed = 0

def drive(self, distance):
        time = distance / self.speed
        print "time:%.2f" % time

car1 = Car()
car1.speed = 60.0
car1.drive(100.0)
car1.drive(200.0)

car2 = Car()
car2.speed = 150.0
car2.drive(100.0)
car2.drive(200.0)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
time:1.67
time:3.33
time:0.67
time:1.33

Process finished with exit code 0

---------------------------------------------------
52.
# _*_coding:utf-8_*_
# __author__ = '10459'

class Vehicle:
    def __init__(self, speed):      # 定义类的初始化属性(类变量)
        self.speed = speed

def drive(self, distance):
        print 'need %f hour(s)' % (distance / self.speed)

class Bike(Vehicle):
    pass

class Car(Vehicle):
    def __init__(self, speed, fuel):     
 #重新定义类属性,初始化Car类,因为超类中有__init__的方法,所以会覆盖超类,但是超类的初始方法可以直接引用
        Vehicle.__init__(self, speed)      # 不是对象直接调用方法,所以后面需要self参数
        self.fuel = fuel                    # 对父类中类变量初始化增加一个类变量的格式

def drive(self, distance):
        Vehicle.drive(self, distance)
        print 'need %f fuels' %(distance * self.fuel)      
  # 对于类方法中定义含有参数的不用加self,假如定义方法不含有的参数,则需要加上self

b = Bike(15.0)
c = Car(80.0, 0.012)
b.drive(100.0)
c.drive(100.0)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
need 6.666667 hour(s)
need 1.250000 hour(s)
need 1.200000 fuels

Process finished with exit code 0
-------------------------------------------------
53.python中and-or的技巧
print bool and a or b 一般是按顺序执行的,与c语言中的bool?a:b类似,有点区别的地方就是a不能
为假,比如a='',则运行的结果会与想象不一致。
# _*_coding:utf-8_*_
# __author__ = '10459'

a = [""]
b = []
c = [0]
print bool(a), bool(b), bool(c)   # bool(a) 为真,bool(b)为假,bool(c)为真

a = "heaven"    # a为字符串有值,为真
b = "hell"      # b为字符串有值,为真
c = True and a or b  # 有点类似与c语言bool?a:b  bool为真时,结果为a,bool为假时,结果为b
print c
d = False and a or b  # 假如a也为假,则print c结果不符合c语言的方式
print d

# 假如a为假,则需用以下方式
a = ''
b = 'hell'
c = True and a or b
print "c:" + c
d = (True and [a] or [b])[0]
print "d:" + d

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
True False True
heaven
hell
c:hell
d:

Process finished with exit code 0
--------------------------------------------------
54.元组  格式:(x,y,z)元组也可以像list一样索引,切片以及遍历
# _*_coding:utf-8_*_
# __author__ = '10459'

# 元组的切片,索引,遍历
position = (1, 2)
greeks = ('Sheldon', "dkfls", "skdl", 'sfjskjf')
print position[0]   #索引
print position[1]
for g in greeks: #遍历
    print g
print greeks[1:3] #切片
print greeks[1:-1]
print '%s is %d years old' % ('Mike', 23)     
 # 元组常用的方式之一("Mike", 23)就是一个元组

def get_pos(n):
    return n / 2, n * 2

x, y = get_pos(50)          # 返回值有多个情况下赋值方式一
print x
print y
print (x, y)                # 打印元组(x,)
pos = get_pos(50)           # 返回值有多个的情况下,赋值方式二
print pos[0]
print pos[1]
print (pos[0], pos[1])      # 打印元祖(pos[0], pos[1])

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
1
2
Sheldon
dkfls
skdl
sfjskjf
('dkfls', 'skdl')
('dkfls', 'skdl')
Mike is 23 years old
25
100
(25, 100)
25
100
(25, 100)

Process finished with exit code 0
-------------------------------------------------------
55.数学运算
# _*_coding:utf-8_*_
# __author__ = '10459'

import math

# 函数常用网址:http://docs.python.org/2/library/math.html
# 常量
print math.pi
print math.e

# 数值运算
print math.ceil(1.2)   # 向上取整数如1.3返回2
print math.floor(2.3)  # 向下取整数如2.4返回2

print math.pow(2, 3)    # 指数运算
print math.log(100, 10), math.log(math.pow(math.e, 2))    # 对数运算,默认e为基底,改变基底,可以改变y。

print math.sqrt(100)    # 平方根
print math.fabs(-3)     # 绝对值

# 三角函数
print math.sin(math.pi / 2)    # 参数以弧度为单位,比如π为180°,运算时要换算
print math.cos(math.pi / 4)  #二分之根号二
print math.tan(math.pi / 4)  #1
print math.asin(math.sqrt(3) / 2) #60°
print math.acos(math.sqrt(3) / 2)  # 30°
print math.atan(1)   #45°

print math.degrees(math.pi)    # 弧度转角度  180°
print math.radians(45)          # 角度转换成弧度  π/4

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
3.14159265359
2.71828182846
2.0
2.0
8.0
2.0 2.0
10.0
3.0
1.0
0.707106781187
1.0
1.0471975512
0.523598775598
0.785398163397
180.0
0.785398163397

Process finished with exit code 0
------------------------------------------
56.真值表
#NOT 结果与原值相反
not False 等价于True
not True   等价于 False
#OR 只要有一个为真就为真
True or False 等价于True
True or True 等价于 True
False or True 等价于 True
False or False 等价于 False

# and 两者两个为真才为真
True and False 等价于False
True and True 等价于 True
False and True 等价于 False
False and False 等价于 False
# Not Or
not (True or False)等价于 False
not (True or True)等价于False
not (False or True)等价于False
not (False or False)等价于True

not (True and False) 等价于True
not(True and True) 等价于 False
not(False and True) 等价于 True
not(False and False) 等价于 True
#!=
1!=0 等价于True
1!=1 等价于False
0!=1 等价于True
0!=0 等价于False
# ==
1==0 等价于False
1==1 等价于True
0==1 等价于False
0==0 等价于True
-------------------------------------------------------
57.常用的一些模块课外去学
常用的模块:
random(随机数)
re(正则表达式)
time(时间)
urllib2(网络请求)
PIL(图形处理)
PyXML(解析和处理XML文件)
MySQLdb(连接MySQL数据库)
Tkinter(图形界面接口,python自带)
smtplib(发送电子邮件)
ftplib(ftp编程)
PyMedia(多媒体操作)
PyOpenGL(OpenGL接口)
BeautifulSoup--HTML/XML解析器
------------------------------------------------
58.python 连接数据库DB API
https://www.python.org/dev/peps/pep-0249/
------------------
59.类的实例(定义类要继承object,特别是在2.7版本)
# _*_coding:utf-8_*_
# __author__ = '10459'

class Programer(object):        # 类的定义,包含属性和方法(里面要加object,新式类)
    hobby = "Play games"        # 定义了全局变量,也叫类的属性,调用方式直接是对象.属性,不加括号

def __init__(self, name, age, weight):  # 这是一个类的构造函数,这是一个初始化函数,里面必须要有self必填参数,之后是定义的局部变量
        self.name = name
        self._age = age
        self.__weight = weight

@classmethod            # 这可以理解为一个修饰器,假如加了这个,在调用这个函数的时候可以直接用类名.函数名()调用
    def get_hobby(cls):
        return cls.hobby

@property               # 这是另一个修饰器,假如加了这个,在调用这个函数的时候可以直接用对象名.函数名,不加括号调用,相当于是调用对象属性那样调用
    def get_weight(self):
        return self.__weight   # 这里要注意self后面的参数要和初始化定义的参数一致,比如这里不能写self.weight

def self_introduction(self):
        print "my name is %s,I am %d years old" % (self.name, self._age)

if __name__ == "__main__":
    programer = Programer("张山", 28, 80)
    print dir(programer)        # 打印对象所包含的方法
    print type(programer)       # 打印类型
    print programer.__dict__
    print Programer.get_hobby()  # print打印的是返回值
    Programer.get_hobby()    # 这里里面函数没有print,所以相当于不执行这个东西
    print programer.get_weight
    programer.self_introduction()  # 调用对象的方法不用加 print

def aa():       # 函数定义的时候非必须带参数,但是在类函数定义的时候必须带参数
        print "dd"
        return 1
    print aa()      # 这里执行俩步骤,一个是执行aa(),print如果打印的东西为None,是因为aa()没有返回值,这里有有返回值,则打印1
    aa()           # 仅仅执行aa()函数,所以会有打印

结果如下:
 D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
['_Programer__weight', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_age', 'get_hobby', 'get_weight', 'hobby', 'name', 'self_introduction']
<class '__main__.Programer'>
{'_age': 28, '_Programer__weight': 80, 'name': '\xe5\xbc\xa0\xe5\xb1\xb1'}
Play games
80
my name is 张山,I am 28 years old
dd
1
dd

Process finished with exit code 0
-----------------------------------------------
60.类的继承
# _*_coding:utf-8_*_
# __author__ = '10459'

class Programer(object):        # 类的定义,包含属性和方法(里面要加object,新式类)
    hobby = "Play games"        # 定义了全局变量,也叫类的属性,调用方式直接是对象.属性,不加括号

def __init__(self, name, age, weight):  # 这是一个类的构造函数,这是一个初始化函数,里面必须要有self必填参数,之后是定义的局部变量
        self.name = name
        self._age = age
        self.__weight = weight

@classmethod            # 这可以理解为一个修饰器,假如加了这个,在调用这个函数的时候可以直接用类名.函数名()调用
    def get_hobby(cls):
        return cls.hobby

@property               # 这是另一个修饰器,假如加了这个,在调用这个函数的时候可以直接用对象名.函数名,不加括号调用,相当于是调用对象属性那样调用
    def get_weight(self):
        return self.__weight   # 这里要注意self后面的参数要和初始化定义的参数一致,比如这里不能写self.weight

def self_introduction(self):
        print "my name is %s,I am %d years old" % (self.name, self._age)

class BackendProgramer(Programer):   # 多继承(class B(a,b,c))
    def __init__(self, name, age, weight, language):
        super(BackendProgramer, self).__init__(name, age, weight)  # 继承的格式,貌似构造函数只能在父类基础上增加,或等于,不能减少
        self.language = language

if __name__ == "__main__":
    programer1 = BackendProgramer("张山", 28, 80, "ENGLISH")
    print dir(programer1)        # 打印对象所包含的方法
    print type(programer1)       # 打印类型
    print programer1.__dict__    # 输出对象构造函数的属性和对应的值,属性有多少个就显示多少属性对应的值
    print isinstance(programer1, Programer)  # 判断programer1这个对象是否属于Programer这个类中的
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
['_Programer__weight', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_age', 'get_hobby', 'get_weight', 'hobby', 'language', 'name', 'self_introduction']
<class '__main__.BackendProgramer'>
{'_age': 28, '_Programer__weight': 80, 'name': '\xe5\xbc\xa0\xe5\xb1\xb1', 'language': 'ENGLISH'}
True

Process finished with exit code 0
--------------------------------------------------------------
61.类的多态(包含继承,方法重写俩属性)举个例子,程序员在写电商项目,可以用java,python,c语言写等等,这就是做同一件事情可以有不同的方法。
# _*_coding:utf-8_*_
# __author__ = '10459'

class Programer(object):        # 类的定义,包含属性和方法(里面要加object,新式类)
    hobby = "Play games"        # 定义了全局变量,也叫类的属性,调用方式直接是对象.属性,不加括号

def __init__(self, name, age, weight):  # 这是一个类的构造函数,这是一个初始化函数,里面必须要有self必填参数,之后是定义的局部变量
        self.name = name
        self._age = age
        self.__weight = weight

@classmethod            # 这可以理解为一个修饰器,假如加了这个,在调用这个函数的时候可以直接用类名.函数名()调用
    def get_hobby(cls):
        return cls.hobby

@property               # 这是另一个修饰器,假如加了这个,在调用这个函数的时候可以直接用对象名.函数名,不加括号调用,相当于是调用对象属性那样调用
    def get_weight(self):
        return self.__weight   # 这里要注意self后面的参数要和初始化定义的参数一致,比如这里不能写self.weight

def self_introduction(self):
        print "my name is %s,I am %d years old" % (self.name, self._age)

class BackendProgramer(Programer):
    def __init__(self, name, age, weight, language):
        super(BackendProgramer, self).__init__(name, age, weight)
        self.language = language

def self_introduction(self):
        print "my name is %s,my favorite languaue is %s" % (self.name, self.language)   # 对继承类方法修改的时候要用self.属性

def introduce(progamer):
    if isinstance(progamer, Programer):
        progamer.self_introduction()

if __name__ == "__main__":
    programer = Programer("大大", 34, 56)
    programer1 = BackendProgramer("张山", 28, 80, "ENGLISH")
    introduce(programer)    # 多态,同一种方法,不同对象可以用不同的思维
    introduce(programer1)   # 多态,同一种方法,不同对象不同思维
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test1.py"
my name is 大大,I am 34 years old
my name is 张山,my favorite languaue is ENGLISH

Process finished with exit code 0
------------------------------------------
62.面向对象范例
# _*_coding:utf-8_*_
# __author__ = '10459'

class Employee(object):
    u"""所有员工的基类"""  # 类文档帮助字符串 用类名.__doc__可以查看
    empCount = 0

def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

def displayCount(self):
        print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
        print "Name : ", self.name,  ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.  # 类的属性(包含一个字典,由类的数据属性组成)
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Test2.py"
Employee.__doc__: 所有员工的基类   # 类的文档字符串
Employee.__name__: Employee     # 类名
Employee.__module__: __main__      # 类所在的模块,类的全名:__main__.ClassName
Employee.__bases__: (<type 'object'>,)# 类的所有父类构成元素(包含了一个所有父类组成的元组)
Employee.__dict__: {'displayEmployee': <function displayEmployee at 0x0000000002FEDC88>, '__module__': '__main__', 'displayCount': <function displayCount at 0x0000000002FEDC18>, '__dict__': <attribute '__dict__' of 'Employee' objects>, 'empCount': 0, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': u'\u6240\u6709\u5458\u5de5\u7684\u57fa\u7c7b', '__init__': <function __init__ at 0x0000000002FEDBA8>}

Process finished with exit code 0
---------------------------------------------------------------
63.面向对象实例
# _*_coding:utf-8_*_
# __author__ = '10459'

class Test(object):
    def prt(self):
        print(self)   # 打印self
        print(self.__class__) # 打印self所属的类

t = Test()  # 实例化对象
t.prt()     # 利用对象调用类方法
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/Test2.py"
<__main__.Test object at 0x00000000023D0E10>
<class '__main__.Test'>

Process finished with exit code 0
------------------------------------------
64.%s,%r的区别与相同
%r用rper()方法处理对象
%s用str()方法处理对象
有时我们并不知道自己打印的神马信息,可以用%r打印
有些情况下,两者处理的结果是一样的,比如说处理int型对象,打印字符串类型的时候%r会有单引号,%s并没有引号,打印日期的时候格式不一样。
例一:

print "I am %d years old." % 22
print "I am %s years old." % 22
print "I am %r years old." % 22

返回结果:

I am 22 years old.
I am 22 years old.
I am 22 years old.

另外一些情况两者就不同了

例二:

text = "I am %d years old." % 22
print "I said: %s." % text
print "I said: %r." % text

返回结果:

I said: I am 22 years old..
I said: 'I am 22 years old.'. // %r 给字符串加了单引号

再看一种情况

例三:

import datetime
d = datetime.date.today()
print "%s" % d
print "%r" % d

返回结果:
2014-04-14
datetime.date(2014, 4, 14)
-------------------------------------
65.遍历实例(包含字符串,列表,字典)
# _*_coding:utf-8_*_
# __author__ = '10459'

for i in "hello world":
    print i,
print
fruit = ["apple", "banana", "orange", "grape"]
for i in fruit:
    print i,
print
for i in range(5):
    print i,
print
for i in range(1, 10, 2):
    print i,
print
abc = ["we", "dd", 2, 'ee']
abc[2] = 'ff'
print abc,
print
dicts = {'username': "zhangxiaozeng", "password": "qweqwe123"}
print dicts.keys()
print dicts.values()
print dicts.items()
for k, v in dicts.items():  # 遍历字典格式,k表示key,v表示value
    print k
    print v
    print("dicts keys is %r" % k)
    print("dicts values is %r" % v)
"""
zip函数表示合并俩list为字典
"""
keys = ["a", "b", "c", "d", "e"]
values = [1, 2, 3, 4, 5]
for key, value in zip(keys, values):
    print key, value
i = 1
b = 2
print (i, b)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
h e l l o   w o r l d
apple banana orange grape
0 1 2 3 4
1 3 5 7 9
['we', 'dd', 'ff', 'ee']
['username', 'password']
['zhangxiaozeng', 'qweqwe123']
[('username', 'zhangxiaozeng'), ('password', 'qweqwe123')]
username
zhangxiaozeng
dicts keys is 'username'
dicts values is 'zhangxiaozeng'
password
qweqwe123
dicts keys is 'password'
dicts values is 'qweqwe123'
a 1
b 2
c 3
d 4
e 5
(1, 2)

Process finished with exit code 0
---------------------------------------------
66.定义函数return与非return的区别,以及默认参数
return要打印的时候return内容才会输出
而非return的话,定义函数有print的话就直接调用,无需重新打印
# _*_coding:utf-8_*_
# __author__ = '10459'

def add(a, b):
    return a + b
print add(3, 5)

def add1(a, b):
    print (a + b)
add1(3, 5)

"""
函数定义时设置默认参数,这样的话假如懒得在调用的时候添加参数的话,会有一个默认值
"""

def add2(a=1, b=2):
    return a + b
print add2()
print add2(3, 4)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
8
8
3
7

Process finished with exit code 0

--------------------------------------
67.类的简单实例
# _*_coding:utf-8_*_
# __author__ = '10459'

class A(object):
    def add(self, a, b):
        return a + b
count = A()
print count.add(3, 4)

class B(object):
    def __init__(self, a, b):
        self.a = int(a)
        self.b = int(b)

def add1(self):
        return self.a+self.b
count1 = B(3, 4)
print count1.add1()
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
7
8
10
-1

Process finished with exit code 0
-------------------------------------------------------
68.模组实例
# _*_coding:utf-8_*_
# __author__ = '10459'

from time import *   # 引用time模块下所有方法,直接可以引用函数

print(ctime())       # ctime()打印当前时间,返回格式string格式
print type(ctime())
print "休眠俩秒"
sleep(2)           # 休眠两秒,没有返回类型
print type(sleep(2))
print(ctime())

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
Sun Aug 06 19:36:47 2017
<type 'str'>
休眠俩秒
<type 'NoneType'>
Sun Aug 06 19:36:51 2017

Process finished with exit code 0
----------------------------------------------------
69.查看模块帮助
# _*_coding:utf-8_*_
# __author__ = '10459'

import time
help(time)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
Help on built-in module time:

NAME
    time - This module provides various functions to manipulate time values.

FILE
    (built-in)

DESCRIPTION
    There are two standard representations of time.  One is the number
    of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
    or a floating point number (to represent fractions of seconds).
    The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
    The actual value can be retrieved by calling gmtime(0).
   
    The other representation is a tuple of 9 integers giving local time.
    The tuple items are:
      year (four digits, e.g. 1998)
      month (1-12)
      day (1-31)
      hours (0-23)
      minutes (0-59)
      seconds (0-59)
      weekday (0-6, Monday is 0)
      Julian day (day in the year, 1-366)
      DST (Daylight Savings Time) flag (-1, 0 or 1)
    If the DST flag is 0, the time is given in the regular time zone;
    if it is 1, the time is given in the DST time zone;
    if it is -1, mktime() should guess based on the date and time.
   
    Variables:
   
    timezone -- difference in seconds between UTC and local standard time
    altzone -- difference in  seconds between UTC and local DST time
    daylight -- whether local time should reflect DST
    tzname -- tuple of (standard time zone name, DST time zone name)
   
    Functions:
   
    time() -- return current time in seconds since the Epoch as a float
    clock() -- return CPU time since process start as a float
    sleep() -- delay for a number of seconds given as a float
    gmtime() -- convert seconds since Epoch to UTC tuple
    localtime() -- convert seconds since Epoch to local time tuple
    asctime() -- convert time tuple to string
    ctime() -- convert time in seconds to string
    mktime() -- convert local time tuple to seconds since Epoch
    strftime() -- convert time tuple to string according to format specification
    strptime() -- parse string to time tuple according to format specification
    tzset() -- change the local timezone

CLASSES
    __builtin__.object
        struct_time
   
    class struct_time(__builtin__.object)
     |  The time value as returned by gmtime(), localtime(), and strptime(), and
     |  accepted by asctime(), mktime() and strftime().  May be considered as a
     |  sequence of 9 integers.
     | 
     |  Note that several fields' values are not the same as those defined by
     |  the C language standard for struct tm.  For example, the value of the
     |  field tm_year is the actual year, not year - 1900.  See individual
     |  fields' descriptions for details.
     | 
     |  Methods defined here:
     | 
     |  __add__(...)
     |      x.__add__(y) <==> x+y
     | 
     |  __contains__(...)
     |      x.__contains__(y) <==> y in x
     | 
     |  __eq__(...)
     |      x.__eq__(y) <==> x==y
     | 
     |  __ge__(...)
     |      x.__ge__(y) <==> x>=y
     | 
     |  __getitem__(...)
     |      x.__getitem__(y) <==> x[y]
     | 
     |  __getslice__(...)
     |      x.__getslice__(i, j) <==> x[i:j]
     |     
     |      Use of negative indices is not supported.
     | 
     |  __gt__(...)
     |      x.__gt__(y) <==> x>y
     | 
     |  __hash__(...)
     |      x.__hash__() <==> hash(x)
     | 
     |  __le__(...)
     |      x.__le__(y) <==> x<=y
     | 
     |  __len__(...)
     |      x.__len__() <==> len(x)
     | 
     |  __lt__(...)
     |      x.__lt__(y) <==> x<y
     | 
     |  __mul__(...)
     |      x.__mul__(n) <==> x*n
     | 
     |  __ne__(...)
     |      x.__ne__(y) <==> x!=y
     | 
     |  __reduce__(...)
     | 
     |  __repr__(...)
     |      x.__repr__() <==> repr(x)
     | 
     |  __rmul__(...)
     |      x.__rmul__(n) <==> n*x
     | 
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     | 
     |  tm_hour
     |      hours, range [0, 23]
     | 
     |  tm_isdst
     |      1 if summer time is in effect, 0 if not, and -1 if unknown
     | 
     |  tm_mday
     |      day of month, range [1, 31]
     | 
     |  tm_min
     |      minutes, range [0, 59]
     | 
     |  tm_mon
     |      month of year, range [1, 12]
     | 
     |  tm_sec
     |      seconds, range [0, 61])
     | 
     |  tm_wday
     |      day of week, range [0, 6], Monday is 0
     | 
     |  tm_yday
     |      day of year, range [1, 366]
     | 
     |  tm_year
     |      year, for example, 1993
     | 
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     | 
     |  __new__ = <built-in method __new__ of type object>
     |      T.__new__(S, ...) -> a new object with type S, a subtype of T
     | 
     |  n_fields = 9
     | 
     |  n_sequence_fields = 9
     | 
     |  n_unnamed_fields = 0

FUNCTIONS
    asctime(...)
        asctime([tuple]) -> string
       
        Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
        When the time tuple is not present, current time as returned by localtime()
        is used.
   
    clock(...)
        clock() -> floating point number
       
        Return the CPU time or real time since the start of the process or since
        the first call to clock().  This has as much precision as the system
        records.
   
    ctime(...)
        ctime(seconds) -> string
       
        Convert a time in seconds since the Epoch to a string in local time.
        This is equivalent to asctime(localtime(seconds)). When the time tuple is
        not present, current time as returned by localtime() is used.
   
    gmtime(...)
        gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
                               tm_sec, tm_wday, tm_yday, tm_isdst)
       
        Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
        GMT).  When 'seconds' is not passed in, convert the current time instead.
   
    localtime(...)
        localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                                  tm_sec,tm_wday,tm_yday,tm_isdst)
       
        Convert seconds since the Epoch to a time tuple expressing local time.
        When 'seconds' is not passed in, convert the current time instead.
   
    mktime(...)
        mktime(tuple) -> floating point number
       
        Convert a time tuple in local time to seconds since the Epoch.
   
    sleep(...)
        sleep(seconds)
       
        Delay execution for a given number of seconds.  The argument may be
        a floating point number for subsecond precision.
   
    strftime(...)
        strftime(format[, tuple]) -> string
       
        Convert a time tuple to a string according to a format specification.
        See the library reference manual for formatting codes. When the time tuple
        is not present, current time as returned by localtime() is used.
   
    strptime(...)
        strptime(string, format) -> struct_time
       
        Parse a string to a time tuple according to a format specification.
        See the library reference manual for formatting codes (same as strftime()).
   
    time(...)
        time() -> floating point number
       
        Return the current time in seconds since the Epoch.
        Fractions of a second may be present if the system clock provides them.

DATA
    accept2dyear = 1
    altzone = -32400
    daylight = 0
    timezone = -28800
    tzname = ('\xd6\xd0\xb9\xfa\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4', '\xd6\xd...

Process finished with exit code 0
-------------------------------------
70.模组调用(同目录模块的调用)
自己创建的模块在另一个程序中调用(同一个文件夹下不同py文件函数调用)
步骤如下:先在pycharm中创建一个project名字为mokuai
模块文件夹中创建两个py文件,名字分别为pub.py,count.py,在pub.py定义一个add函数,
# _*_coding:utf-8_*_
# __author__ = '10459'

def add1(a=1, b=2):
    return a + b
之后在count.py文件下
# _*_coding:utf-8_*_
# __author__ = '10459'

from pub import add1
print add1()
print add1(3, 5)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/count.py"
3
8

Process finished with exit code 0
这样的话就在同一个文件夹下完成了不同py之间方法的调用
----------------------------------------------
71.不同文件夹之间模组的调用
在python2.7下需要讲被import的.py格式的文件里面添加一个__init__.py文件(可以为空,告诉python这里是标准的模块组),同时将.py文件目录路径添加到path变量,可以代码添加也可以手动添加,import执行过程:
1.创建一个新的module对象(它可能包含有多个module)
2.把这个module对象插入到sys.module中
3.装载module对象的代码(如果需要,需先编译)
4.执行新的module中对应的代码
'''
在第三步的时候需要找到mudule程序所在的位置:顺序为,先查找当前路径(以及从当前目录指定的sys.path),然后找pythonPATH,然后再是python安装时设置的相关默认路径,正因为存在这样
的顺序,如果当前路径或pythonPATH中存在与标准module同样的module,则会覆盖标准的module,也就是说如果当前文件夹存在xml.py,则执行import xml,导入的是当前目录下的module,而不是
系统的标准的xml
'''
import sys
sys.path.append("./modelzzz")

from modelzzz.pub1 import add1
print add1()
print add1(3, 5)
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/count.py"
3
8

Process finished with exit code 0
--------------------------
72.异常处理实例
语法为try:
except 子原因:
子原因常见的有:
BaseException:新的所有异常类的基类,可以用它来接受所有类型异常
Exception:所有异常类的基类,但继承于BaseException
AssertionError:assert语句失败
IOError:数据无法正常访问(文件被重命名或被移走)
FileNotFoundError(python3.0以上):不存在的目录或文件
AttributeError:试图访问的对象没有属性
OSError:当系统函数存在返回一个系统相关的错误,包括I/O故障,如找不到文件,磁盘已满引发
NameError:使用一个还未赋值对象变量
IndexError:一个序列超出了范围
SyntaxError:解析器遇到一个语法错误
KeyboardInterrupt:ctrl+c被按下,程序被强行终止
TypeError:传入对象类型与要求不符合
例子:文件找不到错误(pycharm里面编辑器其实有写),文件找不到子原因要用IOError,不能用OSError等其他原因,不然会报异常,类型宽泛警告或者起不到报错提示的作用
异常的抛出机制:
1.如果在运行时发生异常,则解释器会查找相应的处理语句(称为handle)
2.如果在当前函数里没有找到的话,则它会将异常传递给上层的调用函数,看那里能不能处理
3.如果在最外层(全局“main”)还是没有找到的话,那么解释器就会退出,同时打印出Traceback
以便用户找到产生错误的原因(即代码报错了,而没有打印异常)
#例子(常用)
# _*_coding:utf-8_*_
# __author__ = '10459'

try:
    open("tst.txt", "r")
except IOError as err:#把IOError的信息用err变量打印出来,except IOError, err:也可以
    print err

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
[Errno 2] No such file or directory: 'tst.txt'

Process finished with exit code 0
----------------------------------------
73. try: except 子原因(类名): else:(只有在try中没有异常的话会执行else的语句)
try: except 子原因: finally:(不管有没有异常,都会打印finally的语句)
例子:(try except else)
# ctrl+/添加注释
1)
# _*_coding:utf-8_*_
# __author__ = '10459'

try:
    #aa = "异常测试"
    print aa
except Exception as err:
    print err
else:
    print "没有异常"

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
name 'aa' is not defined

Process finished with exit code 0
----------------------------------
2)(try except else)
# _*_coding:utf-8_*_
# __author__ = '10459'

try:
    aa = "异常测试"
    print aa
except Exception as err:
    print err
else:
    print "没有异常"
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
异常测试
没有异常

Process finished with exit code 0
------------------------------------------
3)(try except finally)
# _*_coding:utf-8_*_
# __author__ = '10459'

try:
    aa = "异常测试"
    print aa
except Exception as err:
    print err
finally:
    print "有木有异常都会被执行"

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
异常测试
有木有异常都会被执行

Process finished with exit code 0
4)(try except finally)
# _*_coding:utf-8_*_
# __author__ = '10459'

try:
    # aa = "异常测试"
    print aa
except Exception as err:
    print err
finally:
    print "有木有异常都会被执行"

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
name 'aa' is not defined
有木有异常都会被执行

Process finished with exit code 0

-------------------------
74.抛出异常(raise 原因类名(参数))的使用
# _*_coding:utf-8_*_
# __author__ = '10459'

from random import randint
# 生成1-9之间随机的一个整数[1, 9]
number = randint(1, 9)
if number % 2 == 0:
    raise NameError("%d is even" % number)
else:
    raise NameError("%d is odd" % number)
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py"
Traceback (most recent call last):
  File "D:/python-pycharm-installpackage/python script/our test/seleniumtest.py", line 10, in <module>
    raise NameError("%d is odd" % number)
NameError: 3 is odd

Process finished with exit code 1
--------------------------------------------
75.for i in range(10)...else用法
for i in range(10):
    if i == 5:
        print 'found it! i = %s' % i
        break
else:
    print 'not found it ...'
大意是说当迭代的对象迭代完并为空时,位于else的子句将执行,而如果在for循环中含有break时则直接终止循环,并不会执行else子句。
---------------------------------------------------------------
76.selenium定位
# _*_coding:utf-8_*_
#  __author__ = '10459'

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains

# 加载驱动
driver = webdriver.Firefox()
# 设置等待时间,隐式等待,成功的时候立马调整,不成功才会等10秒
driver.implicitly_wait(10)
driver.get("https://www.baidu.com")
# 进入设置并悬浮
sleep(5)
link = driver.find_element_by_xpath(".//*[@id='u1']/a[8]")
ActionChains(driver).move_to_element(link).perform()
# 选择搜索设置
driver.find_element_by_xpath(".//*[@id='wrapper']/div[6]/a[1]").click()
# 保存设置
driver.find_element_by_class_name("prefpanelgo").click()
# 接受js弹窗提示
driver.switch_to.alert.accept()

sleep(5)

driver.quit()
---------------------------
77.通过send_keys来上传文件
# _*_coding:utf-8_*_
# __author__ = '10459'

from selenium import webdriver
from time import sleep
import os

driver = webdriver.Firefox()
file_path = 'file:///' + os.path.abspath('upload.html')
driver.get(file_path)
'''
这样也可以
driver.find_element_by_name("file").send_keys(r'C:\Users\10459\Desktop\fileupload.txt')
'''
driver.find_element_by_name("file").send_keys('C:\Users\\10459\Desktop\\fileupload.txt')
sleep(5)
driver.quit()
------------------------------------------------------
# _*_coding:utf-8_*_
#  __author__ = '10459'

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox()
# 隐式等待
driver.implicitly_wait(10)
driver.get("https://www.baidu.com")
# 通过xpath来定位元素并悬浮
sleep(5)
link = driver.find_element_by_xpath(".//*[@id='u1']/a[8]")
ActionChains(driver).move_to_element(link).perform()
# 通过xpath来定位元素并点击
driver.find_element_by_xpath(".//*[@id='wrapper']/div[6]/a[1]").click()
# 通过xpath来定位元素并点击
driver.find_element_by_class_name("prefpanelgo").click()
sleep(5)
# 接受js弹窗switch_to.alert.accept()
driver.switch_to.alert.accept()

sleep(5)

driver.quit()
-------------------------------
78.操作cookie
# _*_coding:utf-8_*_
# __author__ = '10459'

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get("http://www.youdao.com/")
driver.add_cookie({u"name": u"hehe", u"value": u"345"})
cookie_1 = driver.get_cookies()
for cookie in cookie_1:
    print "%s --> %s" % (cookie[u"name"], cookie[u"value"])
time.sleep(5)
driver.quit()
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test9.py"
YOUDAO_MOBILE_ACCESS_TYPE --> 1
DICT_UGC --> be3af0da19b5c5e6aa4e17bd8d90b28a|
OUTFOX_SEARCH_USER_ID --> -363003268@61.141.156.231
JSESSIONID --> abcKmfMiLEqlY-aEo6A3v
___rl__test__cookies --> 1502616407613
OUTFOX_SEARCH_USER_ID_NCOO --> 418032825.84904164
hehe --> 345

Process finished with exit code 0
----------------------------------------------
79.selenium截图(本浏览器缩小就截取不到了)
# _*_coding:utf-8_*_
# __author__ = '10459'

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
time.sleep(5)
driver.get_screenshot_as_file(r'C:\Users\10459\Desktop\baidu.jpg')
time.sleep(5)
driver.quit()
---------------------------
80.selenium滚动条(缩小浏览器就不行了,不知道为啥)
# _*_coding:utf-8_*_
# __author__ = '10459'

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
time.sleep(5)
# driver.get_screenshot_as_file(r'C:\Users\10459\Desktop\baidu.jpg')
js = "window.scrollTo(0, 450);"#没缩小页面
driver.execute_script(js)
time.sleep(5)
driver.quit()
----------------------------------------------
81.通过selenium操作html视频
# _*_coding:utf-8_*_
# __author__ = '10459'

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get("http://videojs.com")
driver.implicitly_wait(30)
video = driver.find_element_by_id("preview-player_html5_api")
url = driver.execute_script("return arguments[0].currentSrc;", video)
print url
print "start 20 seconds"
driver.execute_script("return arguments[0].play()", video)
time.sleep(20)
print "stop"
driver.execute_script("return arguments[0].pause()", video)
time.sleep(10)
time.sleep(5)
driver.quit()
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/test10.py"
http://vjs.zencdn.net/v/oceans.mp4
start 20 seconds
stop

Process finished with exit code 0

-----------------------------------
82.静态方法

# _*_coding:utf-8_*_
# __author__ = '10459'

class TestClassMethod(object):

METHOD = 'method hoho'

def __init__(self):
        self.name = 'leon'

def test1(self):
        self.test3()
        print 'test1'
        print self

@classmethod
    def test2(cls):
        print cls
        print 'test2'
        print cls.METHOD
        print TestClassMethod.METHOD
        print '----------------'

@staticmethod
''' 静态方法声明,里面可以不带参数,可以通过类调用,一般通过类调用,可以有参数,也可以有返回,也可以通过实例化(self或实例化调用)调用,但是不能访问实例属性
'''
    def test3():
        print TestClassMethod.METHOD
        print 'test3'

if __name__ == '__main__':
    a = TestClassMethod()
    a.test1()
    a.test2()
    a.test3()
    TestClassMethod.test3()
--------------------------------------
83.静态方法(调用静态方法,创建的对象不会之间自动执行__init__方法)
# _*_coding:utf-8_*_
# __author__ = '10459'

import time

class Date:
    def __init__(self, year, month, day):
        self.year=year
        self.month=month
        self.day=day

@staticmethod
    def now():
        t=time.localtime()
        return Date(t.tm_year, t.tm_mon, t.tm_mday)

def sss(self):
        print "ssdff"
        return 1

class EuroDate(Date):
    def __str__(self):
        return 'year:%s month:%s day:%s' % (self.year, self.month, self.day)

e=Date.now()
e.sss()
print e  # 我们的意图是想触发EuroDate.__str__,但是结果为内存
print e.sss() 
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/count.py"
ssdff
<__main__.Date instance at 0x0000000002D841C8>
ssdff
1

Process finished with exit code 0
类方法的使用
# _*_coding:utf-8_*_
# __author__ = '10459'
import time

class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
        print "ddff"
    # @staticmethod
    # def now():
    #     t=time.localtime()
    #     return Date(t.tm_year,t.tm_mon,t.tm_mday)

@classmethod  # 改成类方法
    def now(cls):
        t=time.localtime()
        return cls(t.tm_year,t.tm_mon,t.tm_mday) 
  # 哪个类来调用,即用哪个类cls来实例化,返回一个对象(包含类,属性)

class EuroDate(Date):
    def __str__(self):
        return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)

'''
我们的意图是想触发EuroDate.__str__,此时e就是由EuroDate产生的,所以会如我们所愿
'''
e = EuroDate.now()  # 会执行Date下面__init__方法
print Date.now()  # 会执行Date下面__init__方法
print(e)  # 打印返回值
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/count.py"
ddff
ddff
<__main__.Date instance at 0x0000000003934148>
year:2017 month:8 day:20

Process finished with exit code 0
--------------------------------------
84.简单自动化脚本(selenium+python)163邮箱登陆退出案例
当前路径
modelzzz文件夹下pub1.py文件
count.py文件
from time import sleep

class Login(object):
    def user_login(self, driver):
        driver.find_element_by_id("idInputLine").send_keys("aisidifi8zhx")
        sleep(5)
        driver.find_element_by_id("pwdPlaceholder").send_keys("password******")
        sleep(5)
        driver.find_element_by_id("btnSubmit").click()
        sleep(5)
        print "after login"
        title = driver.title
        print title
        now_url = driver.current_url
        print now_url
        sleep(5)
        user = driver.find_element_by_id("spnUid").text
        print user
        sleep(10)

def user_logout(self,driver):
        driver.find_element_by_link_text(u"退出").click()
        driver.quit()
用例:
from modelzzz.pub1 import Login
from selenium import webdriver

if __name__ == "__main__":
    driver = webdriver.Firefox()
    driver.implicitly_wait(30)
    driver.get("http://email.163.com/#from=ntes_product")

# 调用登陆模块
    Login().user_login(driver)
    # 调用退出模块
    Login().user_logout(driver)
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/count.py"
after login
网易邮箱6.0版
http://mail.163.com/js6/main.jsp?sid=YBGRhBWHSSYsQDDAbFHHdDCcPWbisQJk&df=email163#module=welcome.WelcomeModule%7C%7B%7D
aisidifi8zhx@163.com

Process finished with exit code 0
--------------------------------------------------
85.自动化测试报告
'''test_Baidu.py'''
# -*-coding:utf-8-*-
# __author__ = '10459'

from selenium import webdriver
import unittest
import time

class Baidu(unittest.TestCase):
    """baidu"""
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.baidu.com/"

def test_Baidu_search(self):
        """keywords:HtmlTestRunner"""
        driver = self.driver
        driver.get(self.base_url)
        driver.find_element_by_id("kw").send_keys("HtmlTestRunner")
        driver.find_element_by_id("su").click()

def tearDown(self):
        time.sleep(5)
        self.driver.quit()
'''test_youdao.py'''
# _*_coding:utf-8_*_
# __author__ = '10459'

from selenium import webdriver
import unittest
import time

class Youdao(unittest.TestCase):
    """Youdao"""
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://www.youdao.com/"

def test_Youdao_search(self):
        """keywords:description"""
        driver = self.driver
        driver.get(self.base_url)
        driver.find_element_by_id("translateContent").send_keys("description")
        driver.find_element_by_xpath(".//*[@id='form']/button").click()

def tearDown(self):
        time.sleep(5)
        self.driver.quit()
runnest.py
# _*_coding:utf-8_*_
# __author__ = '10459'
import unittest
import time
from HTMLTestRunner import HTMLTestRunner

test_dir = './'
discover = unittest.defaultTestLoader.discover(test_dir, pattern="test_*.py")

if __name__ == "__main__":

# 定义报告的存放路径
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    filename = "./" + now + "result.html"
    fp = open(filename, "wb")

# 定义测试报告,title定义报告的标题,description定义报告的副标题
    runner = HTMLTestRunner(stream=fp, title=u"百度搜索测试报告", description=u"用例执行情况:")
    # 运行测试用例
    runner.run(discover)
    # 关闭测试报告
    fp.close()
-----------------------------------
86.python发送邮件
发送1个人
# -*- coding: UTF-8 -*-
#  __author__ = '10459'

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib

def _format_addr(s):
    name, addr = parseaddr(s)       
 # name,addr是元组分别赋值,后边为元组,如a,b=(1,2)表示a=1,b=2
 # parseaddr()解析s(邮箱地址或别的地址),解析后为一个元组,
 # 前面为名字,后面为地址,前面没有名字就是空('',ssdf@qq.com)
    return formataddr((Header(name, 'utf-8').encode(), addr))

from_addr = 'aisidifi8zhx@sina.com'
password = 'password*******'
to_addr = '***********@qq.com'
smtp_server = 'smtp.sina.com'

msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
msg['From'] = _format_addr('Python爱好者<%s>' % from_addr)
msg['To'] = _format_addr("123<%s>" % to_addr)   # 这里昵称可以随便写
msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

try:
    server = smtplib.SMTP(smtp_server, 25)
#   server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()
    print 'send OK'
except Exception, e:
    print str(e)
发送两个人
# -*- coding: UTF-8 -*-
#  __author__ = '10459'

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

from_addr = 'aisidifi8zhx@sina.com'
password = 'aisidifi8zhx,.3'
to_addr = ['1045933569@qq.com', 'wasabizhx@126.com']
smtp_server = 'smtp.sina.com'

msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')  #字典
msg['From'] = _format_addr('Python爱好者<%s>' % from_addr)
msg['To'] = _format_addr("123<%s>;234<%s>" % (to_addr[0], to_addr[1]))
msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

try:
    server = smtplib.SMTP(smtp_server, 25)
#   server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, to_addr[0:2], msg.as_string())
    server.quit()
    print 'send OK'
except Exception, e:
    print str(e)

{'_headers': [('Content-Type', 'text/plain; charset="utf-8"'), ('MIME-Version', '1.0'), ('Content-Transfer-Encoding', 'base64')], '_payload': 'aGVsbG8sIHNlbmQgYnkgUHl0aG9uLi4u\n', '_charset': utf-8, '_default_type': 'text/plain', 'preamble': None, 'defects': [], '_unixfrom': None, 'epilogue': None}

{'_headers': [('Content-Type', 'text/plain; charset="utf-8"'), ('MIME-Version', '1.0'), ('Content-Transfer-Encoding', 'base64'), ('From', '=?utf-8?b?UHl0aG9u54ix5aW96ICF?= <aisidifi8zhx@sina.com>'), ('To', '=?utf-8?q?123?= <1045933569@qq.com>'), ('Subject', '=?utf-8?b?5p2l6IeqU01UUOeahOmXruWAmeKApuKApg==?=')], '_payload': 'aGVsbG8sIHNlbmQgYnkgUHl0aG9uLi4u\n', '_charset': utf-8, '_default_type': 'text/plain', 'preamble': None, 'defects': [], '_unixfrom': None, 'epilogue': None}

-----------------------
87.元组赋值
# -*- coding: UTF-8 -*-
# __author__ = '10459'

a, b = set([7, 8])
print a, b
a, b = {"nine": 9, "ten": 10}
print a, b
a, b = (1, 2)
print a, b
a, b = 1, 2
print a, b
a, b = [3, 4]
print a, b
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/yuanzu.py"
8 7
nine ten
1 2
1 2
3 4

Process finished with exit code 0
------------------------------------------------
88.python 星号*把序列/集合解包(unpack)成位置参数,两个星号**把字典解包成关键字(字典)参数。函数里参数的顺序为(必传参数,选传参数
,*位置参数元组,**关键字参数字典)
def foo(*args, **kwarg):
    for item in args:
        print item
    for k, v in kwarg.items():
        print k, v
    print 30*'='

if __name__ == '__main__':
    # foo(1, 2, 3, a=4, b=5)
    # foo(2, 3, a=4, b=5, c=1)
    v = (1, 2, 4)
    v2 = [11, 15, 23]
    d = {'a': 1, 'b': 12}
    foo(v)
    foo(*v, **d)
    foo(v2, d)
    foo(*v2, **d)
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/yuanzu.py"
(1, 2, 4)
==============================
1
2
4
a 1
b 12
==============================
[11, 15, 23]
{'a': 1, 'b': 12}
==============================
11
15
23
a 1
b 12
==============================

Process finished with exit code 0
上面的示例中如果v、v2、d没有加星号那么就当成了一个参数传递给了函数,如果加了星号那么就会解包后传递给函数。foo(*d, **d)等价于foo(1, 2, 4, a=1, b=12)。
-----------------------------------------------------
89.发送带附件的邮件
# -*- coding: UTF-8 -*-
#  __author__ = '10459'

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.p_w_picpath import MIMEImage
import smtplib

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

from_addr = 'aisidifi8zhx@sina.com'
password = 'aisidifi8zhx,.3'
to_addr = '1045933569@qq.com'
smtp_server = 'smtp.sina.com'
sendfile = open('C:\\Users\\10459\\Desktop\\fileupload.txt', "rb").read()
att = MIMEText(sendfile, "base64", "utf-8")
att1 = MIMEText("dfksflkdklsfds", "plain", "utf-8")
att2 = MIMEText("""<b> Some <i> HTML </i> text </b> and an p_w_picpath.<img alt="" src="cid:p_w_picpath1">good!""", "html", "utf-8")
fp = open('C:\\Users\\10459\\Desktop\\p_w_picpath.jpg', "rb")
msgp_w_picpath = MIMEText(fp.read(), "base64", "utf-8")
fp.close()
msgp_w_picpath["Content-Type"] = "application/octet-stream"
msgp_w_picpath["Content-Disposition"] = "p_w_upload; filename='p_w_picpath.jpg'"
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = "p_w_upload; filename='fileupload.txt'"
magroot = MIMEMultipart("related")
# msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
magroot['From'] = _format_addr('Python爱好者<%s>' % from_addr)
magroot['To'] = _format_addr("123<%s>" % to_addr)
magroot['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()
magroot.attach(att)
magroot.attach(att1)
magroot.attach(att2)
magroot.attach(msgp_w_picpath)

try:
    server = smtplib.SMTP(smtp_server, 25)
#   server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, to_addr, magroot.as_string())
    server.quit()
    print 'send OK'
except Exception, e:
    print str(e)

结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/sendemail.py"
send OK

Process finished with exit code 0
---------------------------------------
90.join链接的只能是字符串,意味着元组和字典里的key都为字符串
1、join()函数
语法:? 'sep'.join(seq)
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
?
2、os.path.join()函数
语法:? os.path.join(path1[,path2[,......]])
返回值:将多个路径组合后返回
注:第一个绝对路径之前的参数将被忽略
#对序列进行操作(分别使用' '与':'作为分隔符)
??
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido
??
??
#对字符串进行操作
??
>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
??
??
#对元组进行操作
??
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
??
??
#对字典进行操作
??
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello
??
??
#合并目录
??
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'
-------------------------------------
91.整合发邮件的功能
from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
from email.mime.multipart import MIMEMultipart
import smtplib
import unittest
import time
import os

"""
自定义发送邮件
"""

def send_mail(file_new):
    def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))
    sendfile = open(file_new, "rb").read()

attr = MIMEText(sendfile, "html", "utf-8")
    att1 = MIMEText("你好", "plain", "utf-8")
    from_addr = 'aisidifi8zhx@sina.com'
    password = 'aisidifi8zhx,.3'
    to_addr = '1045933569@qq.com'
    smtp_server = 'smtp.sina.com'
    attr["Content-Type"] = "text/html"
    attr["Content-Disposition"] = "p_w_upload; filename='test_report.html'"           # 文件的格式要写
    msg = MIMEMultipart("related")
    msg['From'] = _format_addr('Python爱好者<%s>' % from_addr)
    msg['To'] = _format_addr("123<%s>" % to_addr)
    msg['Subject'] = Header('自动化测试报告', 'utf-8').encode()
    msg.attach(att1)
    msg.attach(attr)
    try:
        server = smtplib.SMTP(smtp_server, 25)
        server.login(from_addr, password)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
        print 'send OK'
    except Exception, e:
        print str(e)
"""
查找测试报告目录,找到最新生成的测试报告文件
"""

def new_report(testreport):
    testreport = "D:\\python-pycharm-installpackage\\python script\\our test\\mokuai\\modelzzz"
    lists = os.listdir(testreport)
    lists.sort(key=lambda x: os.path.getmtime(testreport+"\\"+x))
    print u"最新文件:"+lists[-1]
    file = os.path.join(testreport, lists[-1])
    print file
    return file

if __name__ == "__main__":
    test_dir = "./"
    testreport = "D:\\python-pycharm-installpackage\\python script\\our test\\mokuai\\modelzzz"
    discover = unittest.defaultTestLoader.discover(test_dir, pattern="test_*.py")
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    filename = testreport + "\\" + now + "result.html"
    fp = open(filename, "wb")
    runner = HTMLTestRunner(stream=fp, title=u"搜索测试报告", description=u"用例执行情况:")
    runner.run(discover)
    fp.close()
    file = new_report(testreport)
    send_mail(file)
--------------------------------------------------
92.类的函数调用
# _*_coding:utf-8_*_
# __author__ = '10459'

class b(object):
    def __init__(self,name="hehe"):
        self.aa = "dd"
        self.bb = name
        self.flag = False
        print self.bb

def call(self,gg,ss):
        print self.flag, "name:"
        self.flag = not self.flag
        print gg,ss

class a(b):
    def __init__(self, name, sd):
        b.__init__(self,name="hehe")
        self.aa = "cc"
        self.cc = a
        self.bb = name
        self.ss = sd
        self.flag = True
        print "aaaaaaaaaaaaaaa"
        print name

def setName(self, name="dfsd"):
        self.cc = name
        self.call(self,"ddsdf")
        self.call("fffffffffff", "sssssssssssssssssssssssssss")
        print self.flag

class c(b):
    def __init__(self,name="cccccc"):
        super(c,self).__init__(name)
        print"ccccccccccccccccc"

def setName(self,name="kkkkkkk"):
        self.cc = name
        self.call(self,"ssssssssssssss")
        print self.flag
coder = a("add", "ddd")
coder.setName("woshiyizhizhu")
结果:
D:\Python27\python.exe "D:/python-pycharm-installpackage/python script/our test/mokuai/yuanzu.py"
hehe   打印父类中的print,name在下面已经给了hehe
aaaaaaaaaaaaaaa   打印自己类中print
add                打印自己类中print,参数中新传入的name值
True name:          打印setName里面call函数的print
<__main__.a object at 0x0000000003A08BE0> ddsdf  打印setName里面call
False name:                              打印setName里面call函数的print
fffffffffff sssssssssssssssssssssssssss  打印setName里面call函数的print
True                                      打印setName里面print

Process finished with exit code 0
------------------------------------------------
93.类变量,静态变量,类方法,静态方法
#coding:utf-8

class class_name(object):
    class_var = 'I am a class variable' #类变量
    def __init__(self):
        self.instance_var = 'I am a instance varibale'  #成员变量(实例变量)

def instance_method(self,  formal_parameter):
        local_var_in_function = formal_parameter    #实例方法局部变量
        self.local_var_also_in_function = formal_parameter  #实例方法局部变量

def ordinary_function(formal_parameter):
        print "I am an ordinary function, I can't vist class var and intance var"
        print self.instance_var #报错,因此普通函数无法访问成员函数
        print clacc_var#报错,因此普通函数无法访问类变量

@classmethod
    def class_method(cls, formal_parameter): #类方法
        print 'I am class method, I can visit class var and instance var'

print 'I am class method, I am modifying the instance var'
        cls.instance_var = formal_parameter
        print cls.instance_var

print 'I am class method, I am modifying the class var'
        class_var = formal_parameter
        print class_var

@staticmethod
    def static_method(formal_parameter):
        print 'I am static method, I am the Adopted son(干儿子) for this class!!'

print "I can't modify anything in the class "
        #print class_var
        #print self.instance_var

print 'Get a class instance'
class_instance = class_name()
print '\r'
print "My name is class_instance, I can call class_method, " \
      "statics_method, instance_method and instance_method, but I can't call ordinary_function"
print "I can show you:"
print '\r'
class_instance.class_method('class method is calling!!')
print '\r'
class_instance.static_method('static method in calling!!')
print '\r'
class_instance.instance_method('instance method is calling!!')
print '\r'
print 'class var is calling!!'
print class_instance.class_var
print '\r'
print 'instance var is calling!!'
print class_instance.instance_var
print '\r'
print 'Get a class!!'
print '\r'
print 'My name is class_name, I can call class_method, statics_method, instance_method, instance_method, and ordinary_function'
print "I can show you:"
print '\r'
class_name.class_method('class method is calling!!')
print '\r'
class_name.static_method('static method in calling!!')
print '\r'
#class_name.instance_method("instance method can't be calling!!")
print '\r'
print 'class var is calling!!'
print class_name.class_var
print '\r'
print 'instance var is calling!!'
print class_name.instance_var
print 'END!!'

Result:
Get a class instance

My name is class_instance, I can call class_method, statics_method, instance_method and instance_method, but I can't call ordinary_function
I can show you:

I am class method, I can visit class var and instance var
I am class method, I am modifying the instance var
class method is calling!!
I am class method, I am modifying the class var
class method is calling!!

I am static method, I am the Adopted son(干儿子) for this class!!
I can't modify anything in the class

class var is calling!!
I am a class variable

instance var is calling!!
I am a instance varibale

Get a class!!

My name is class_name, I can call class_method, statics_method, instance_method, instance_method, and ordinary_function
I can show you:

I am class method, I can visit class var and instance var
I am class method, I am modifying the instance var
class method is calling!!
I am class method, I am modifying the class var
class method is calling!!

I am static method, I am the Adopted son(干儿子) for this class!!
I can't modify anything in the class

class var is calling!!
I am a class variable

instance var is calling!!
class method is calling!!
END!!
---------------------------------------------
#全局变量“整数,字符串在局部变量可以改”
#而全局变量字典,集合,列表在局部变量是可以改的

转载于:https://blog.51cto.com/13452915/1979038

pyton笔记-part1相关推荐

  1. 游戏黑客圣经GHB1学习笔记 part1(1-5)

    游戏黑客圣经(Game Hacking Bible1) 我在这里记录我所有课程的学习笔记,包括一些小技巧以及源码,俗话说好记性不如烂笔头,写在这里,用于温故而知新. 前言 学习游戏黑客的必备条件 智力 ...

  2. 计算机网络笔记Part1 概述

    本人计算机网络笔记总目录 计算机网络笔记Part1 概述 计算机网络笔记Part2 物理层(Physical Layer) 计算机网络笔记Part3 数据链路层(Data Link Layer) 计算 ...

  3. 计算机网络学习笔记Part1

    计算机网络学习笔记Part1 1. 概念 计算机网络:是一个将分散的.具有独立功能的计算机系统,通过通信设备与线路连接起来,由功能完善的软件实现资源共享和信息传递的系统. 2.功能 1.数据通信.2. ...

  4. 尚医通项目学习笔记Part1

    尚医通项目学习笔记 前言 一.目前学习进度 二.学习记录 1.项目简介 1.1 项目所会用到的技术栈 1.2 业务流程 2.项目学习笔记 2.1MyBatis-Plus相关 2.2搭建项目框架 2.3 ...

  5. 《算法笔记》学习笔记 part1

    一.  前言 我开始写这篇笔记时,2019年研究生考试已经过去一周了,虽然还不知道初试结果,但还是要开始准备复试了.复试中机试又占了很大的比例,故这里开始复习算法知识了,主要用书为<算法笔记&g ...

  6. 机器学习笔记(part1)--Frobenius范数与迹运算

    学习笔记,仅供参考,有错必纠 转载自:Frobenius范数 迹运算 设A是m×nm \times nm×n的矩阵,其Frobenius范数定义为: ∥A∥F=∑i=1m∑j=1n∣aij∣2{\pa ...

  7. 投资学习网课笔记(part1)--基金第一课

    学习笔记,仅供参考 文章目录 基金第一课 财务自由 什么资产长期收益率更高 通货膨胀 基金第一课 财务自由 财务自由的含义 持有能产生现金流的资产,当每年的现金流,可以覆盖家庭支出,就可以实现财务自由 ...

  8. 《乌合之众》读书笔记(part1)--对群体而言,最不公正的也许却是最好的

    摘抄书中论点,不代表个人观点,仅供学习参考 书籍:<乌合之众:大众心理研究>–古斯塔夫·勒庞 乌合之众 勒庞认为,群体的头脑处于更为原始和本能的状态,导致行为趋于野蛮.个人行为总是趋向理性 ...

  9. 《复杂》读书笔记(part1)--一些思想是由简单的思想组合而成,我称此为复杂

    学习笔记 学习书目:<复杂>- 梅拉妮·米歇尔 文章目录 复杂是什么 复杂系统的共性 如何度量复杂性 复杂是什么 一些思想是由简单的思想组合而成,我称此为复杂:比如美.感激.人.军队.宇宙 ...

最新文章

  1. php微信支付na,虚拟支付
  2. UVA11174村民排队问题
  3. ArcEngine编辑功能的实现(二)
  4. ARM开发培训的总结报告
  5. Spring容器中获取Bean实例的七种方式(附实战源码)
  6. Redis桌面客户端 Redis Studio
  7. c语言xuanzeti1,c语言选择题库1
  8. Codeforces Round #409 (rated, Div. 2, based on VK Cup 2017 Round 2)C. Voltage Keepsake
  9. 95-10-070-启动-SocketServer启动
  10. 学习ssm框架一般要用多少时间
  11. mysql bit类型 查询_数据库中的bit类型
  12. Arcgis土地利用转移矩阵制作
  13. 【LaTeX入门】02、CJK环境讲解
  14. Java调用百度/高德地图API实现根据经纬度查地名
  15. top和iostat指令的使用,linux负载,swap与内存,io
  16. Python爬虫:用最普通的方法爬取ts文件并合成为mp4格式
  17. Error creating bean with name 'redisTemplate' defined in URL
  18. 黑帽实战 | 给大家讲讲一个二类电商的大佬的故事!
  19. 世界数学难题——哥尼斯堡七桥问题 哥尼斯堡七桥问题
  20. Neuraldecipher-逆向工程:从扩展连接性指纹(ECFPs)到其分子结构

热门文章

  1. 夕拾朝花——我的2016
  2. 看电视剧《天道》一点感想 + 法兰克福美景Opencv聚类分析
  3. js中数组的高逼格操作(filter、sort、map、reduce)
  4. 植物大战僵尸音乐计算机简谱,植物大战僵尸(主题音乐)钢琴谱
  5. 漫画行业有妖气:曾经的一哥,今日的难兄
  6. C语言的部分杂碎知识
  7. [NLP]高级词向量表达之ELMo详解
  8. 屏蔽 FutureWarning
  9. linux中centos8.4配置静态ip
  10. 西门子PLC能否通过以太网数据模块实现无线通讯?