安装:python 3.7
https://www.liaoxuefeng.com/wiki/1016959663602400/1017032074151456
1.基础语法:
print("") print(’’) 输出语句,支持单引号和双引号,
#注释
print('A','B','C')#多个字符串得时候,要用单引号,输出 A B C
print(2**10) #1024
print("100+100=",100+100) #100+100=200
name=input('请输入你的名字...')#提示
print('hello',name)#输入 小鸽子 输出 hello 小鸽子
以#开头的是注释语句,可以是任意内容,解释器会忽略掉注释。语句是以冒号:结尾时,缩进的语句视为代码块。(4个空格的缩进。)
缩进的坏处就是复制粘贴功能失效了。每次赋值粘贴的时候必须重新检查缩进是否正确。python对大小写敏感,区分大小写。
b=input('请输入一个数字')
a=int(b)
if a>5:
print('abs(a)',abs(a))#根据缩进量来决定是不是一个方法体
print('执行了吗')#缩进符号必须为英文的空格
else :
print('abs(a)',-abs(a))
print('执行了!')
1.1数据类型
- 整数
- 浮点数 很大或者很小得浮点数要用科学计数法表示把10用e替代,1.23*10的9次方 就是1.23e9或者是12.3e8
- 字符串
- 布尔值 True False 。可以用and or 和not运算
- 空值
- 变量
变量可以任意类型赋值
Answer=True
print('结果:',Answer)
if Answer:
print('结果为真')
Answer='我是字符串'
print('结果:',Answer)
Answer=100
print('结果:我是数字',Answer)
格式化 占位符
%d 整数 %f 浮点数 %s 字符串 %x 十六进制整数
'hello,%s,you have $%d.' %('小鸽子',10000)
print('hello,%s,you have $%d.' %('小鸽子',10000))
#hello,小鸽子,you have $10000.
这两行代码,第一行注释是告诉linux/OS X系统,这是一个python可执行程序,windows系统会忽略这个注释;
第二行注释是为了告诉python解释器按照UTF-8编码读取源码,否则在源代码中写中文有可能输出得是乱码。
#!/user/bin/env python3
# -*- coding:utf-8 -*-
1.2 使用list
在命令行模式下:
>>> persons =['路人甲','路人乙','路人丙']
>>> persons
['路人甲','路人乙','路人丙']
>>> len(persons) #list长度
3
>>> persons[0] #索引位置0的元素
'路人甲'
>>> persons[3] #越界错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> persons[-1] #可以获取倒数第一个元素
'路人丙'
>>> persons.append('路人丁') #追加元素
>>> persons
['路人甲','路人乙','路人丙','路人丁']
>>> persons.insert(1,'路人X') #把元素插到指定位置
>>> persons
['路人甲','路人X','路人乙','路人丙','路人丁']
>>> persons.pop() #删除末尾的元素
'路人丁'
>>> persons
['路人甲','路人X','路人乙','路人丙']
>>> persons.pop(1) #删除指定位置1的元素(从0开始)
'路人X'
>>> persons
['路人甲','路人乙','路人丙']
>>> persons[1]='路人戊' #把某个位置的元素替换成别的元素
>>> persons
['路人甲','路人戊','路人丙']
1.3 条件判断
age = 20
if age >= 18: #一定记得加上冒号
print('your age is', age) #要添加英文空格
print('adult')
age=2
if age>=18:
print('your age is',age)
print('adult')
elif age>16:
print('你是青少年',age)
elif age>10:
print('你是少年儿童',age)
else:
print('其他',age)
#输入出生年份
s=input('birth...')
birth=int(s)
if birth<2000:
print('00前')
else:
print('00后')
#循环打印元素
names=['Michael','Bob','Tracy']
for name in names:
print(name)
#可以生成一个整数序列
>>> list(range(5))
[0,1,2,3,4]
#计算 0到100的和
sum=0
for x in range(101):
sum=sum+x
print(sum)
#使用while 计算100以内所有奇数之和
sum=0
n=99
while n>0:
sum+=n
n-=2;
print(sum)
陷入死循环的时候,可以用Ctrl+C退出程序
#键值对 key不存在的话 会报错,一个key只能对应一个value
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
>>>s=([1,2,3,3,1])
>>>s
{1,2,3}
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}
>>> a=['c','e','a','d']
>>> a.sort() #排序
>>> a
['a','c','d','e']
1.4.1 调用函数
>>> abs(-100) #绝对值
100
>>> abs(12.34)
12.34
>>> max(1,2,8,4,6) #得到最大值 返回最大值
8
#类型转换
>>> int('12') #字符串转化为整数,非数字的会报错
12
>>> int(12.33) #小数转化为整数
12
>>> folat('12.34') #字符串转化为浮点数
12.34
>>> str(1.23) #浮点数转化成字符串
'1.23'
>>> bool(1) #转化为boolean
True
>>> bool(0)
False
>>> bool('asas')
True
>>> bool('')
False
#可以把函数名赋值给一个变量
>>> a=abs #变量a指向abs函数
>>> a(-1) #所以可以通过变量a调用函数
1
1.4.2 定义函数
>>> def my_abs(x):
... if not isinstance(x,(int,float)): #数据类型检查使用内置函数
raise TypeError('bad operand type')
... if x>=0:
... return x
... else x<0:
... return -x
...
>>> my_abs(-9)
9
#空函数 pass语句可以用来作为占位符
>>> def nop():
pass
#函数返回多个值 一个点移动到另外一个点 给出坐标 位移 角度,就可以算出新坐标
import math
def move(x,y,step,angle=0):
nx= x+step*math.cos(angle)
ny=y-step*math.sin(angle)
return nx,ny
#
>>> def power(x,n=2):
s=1
while n>0:
n=n-1
s=s*x
return s
>>> power(5) #相当于power(5,2) 因为有默认参数 必填参数都是前面
2.1 高级特性—切片
>>> L=['Michael', 'Sarah', 'Tracy','Jack']
>>> L[0:3]
['Michael', 'Sarah', 'Tracy']
>>> L[:3] #跟上面代码功能一样都是取1 0到2索引得元素(只有开始是0才可以忽略)
['Michael', 'Sarah', 'Tracy']
>>> L[-2:]
['Tracy','Jack']
>>> L[:10:2]#前10个数 每两个取一个
[0, 2, 4, 6, 8]
>>> L[::5] #所有数字 每5个取一个
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
>>> L[:] #什么都不写就是原样输出
>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'
2.2 高级特性—列表生成式
>>> L=[]
>>> for x in range(1,11):
... L.append(x*x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x*x for x in range(1,11) if x%2==0] #筛选出偶数的平方
[4,16,36,64,100]
>>> import os #导入os模块
>>> [d for d in os.listdir(',')] #可以列出当前目录下所有文件和目录名
['文件夹A','文件夹B']
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello','world','ibm','apple']
>>> L1 = ['Hello', 'World', 18, 'Apple', None]
>>> L2 =[s.lower() for s in L1 if isinstance(s,str)]
>>> L2
['Hello', 'World', 'Apple']
3.1 函数式编程 高阶函数
map reduce
>>> def f(x):
... return x*x
...
>>> r=map(f,range(9))
>>> list(r)
[0,1,4,9,16,25,36,49,64]
>>> list(map(str,range(9)))
['0','1','2','3','4','5','6','7','8']
>>> def add(x,y,f): #让函数的参数能够接收别的参数
... return f(x)+f(y)
...
>>> add(-5,6,abs)
11
>>> def normalize(name):
... return name[0].upper()+name[1:].lower()
...
>>> L1=['adam','LISA','barT']
>>> L2=list(map(normalize,L1))
>>> print(L2)
['Adam','Lisa','Bart']
#编写一个函数求积
from functools import reduce
>>> def cheng(x,y):
... return x*y
>>> def prod(L):
... return reduce(cheng,L)
filter函数用于过滤序列
>>> def is_odd(n):
... return n%2==1
...
>>> L=range(100)
>>> print(list(filter(is_odd,L)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
>>> def not_empty(s):
... return s and s.strip()
...
>>> print(list(filter(not_empty,['B',None,' ','A','','C'])))
['B','A','C']
sorted 排序算法
>>> sorted([36,5,-12,9,-21])
[-21, -12, 5, 9, 36]
>>> sorted(['bob', 'about', 'Zoo', 'Credit']) #字符串排序
['Credit', 'Zoo', 'about', 'bob']
>>> sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower) #字符串排序 忽略大小写
['about', 'bob', 'Credit', 'Zoo']
>>> sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower, reverse=True) #字符串排序 忽略大小写,逆序排列
返回函数
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
>>> f=lazy_sum(1,3,5,7,9)
>>> f #这个返回得是函数
<function lazy_sum.<locals>.sum at 0x000001C0C5BA7AE8>
>>> f() #这个才是真正的求和结果
25