第一个Python程序
>>>print("Hello World!")
Hello World!
退出
exit()
输入输出
输出
>>>print('The quick brown fox','jumps over','the lazy dog')
The quick brown fox jumps over the lazy dog
输入
>>>name=input()
Demo
>>>name
'Demo'
>>>print(name)
'Demo'
>>>print('hello,',name)
hello, Demo
获取用户输入
x = input("x:") # x为string如果想换成int直接int(x)后面还会讲 eval()函数。
``
#成员资格:
user_name= [“DemoD_”,“DemoLi”]
input(“Enter your user name”) in user_name
“\”可以跨行
#数据类型和变量
##数据类型
###整数 浮点数 字符串 布尔值
内置的简单函数
pow(x,y)
pow(x,y,z) #等价于对Pow(x,y)求z模
asb(x)
x**y
round(x) # 四舍五入
//为整除和/区分
str=’ I’m “OK”!’
I’m “OK”!
转义符:在字符串中如果出现引号的话要加转义符(\)
\n表示换行
\t表示制表符
字符\本身也要转义,所以\\表示的符就是\
import math
math.ceil(31.2) #向上取整
32
math.floor(31.2) #向下取整
31
print(‘I’m learning\nPython.’)
I’m learning
Python.print(’\\n\’)
\
True
TrueFalse
False3>2
True3<2
FalseTrue and True
TrueTrue and False
FalseTrue or True
TrueTrue or False
TrueFalse or False
Falsenot False
True
### 空值
空值是Python里一个特殊的值,用None表示。None不能理解为0,因为0是有意义的。
type(None)
<class ‘NoneType’>
### 常量
例如pi
import math
math.pi
3.14592653…dir(math)#会把math库的所有方法输出
[‘doc’,‘name’,…‘e’,‘pi’,‘tan’,‘sqrt’]math.name
‘math’
因为数据的存储原因小数会实际的数不相等,用round()函数处理
0.3+0.3
0.60.3+0.3+0.3
0.8999999999999round(0.3+0.3+0.3)
1
###运算符
+ - * / // %
1+1
21-1
05/2
2.55//2
25%2
1
8 bit=1 byte
1024 byte = 1 kb
1024 kb=1 mb
1024 mb = 1 gb
1024 gb = 1 tb
##字符串和编码
###字符编码
ASCII Unicode UTF-8
对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,
chr()函数把编码转化为对应的字符
ord(‘A’)
65chr(66)
‘B’chr(26991)
‘文’
如果知道字符的整数编码,还可以用十六进制写str
‘\u4e2d\u6587’
‘中文’
'ABC'和b'ABC',前者是str,后者是bytes的每个字符都只占用一个字节
以Unicode表示的str通过encode()方法可以编码为指定的byte()
删除:>del str[i]
‘ABC’.encode(“ascii”)
b.‘ABC’‘中文’.encode(‘utf-8’)
b’\xe4\xb8\xad\xe6\x96\x87’‘中文’.encode(‘ascii’)
报错
纯英文的str可以用ASCII编码为bytes,内容是一样的,含有中文的str可以用UTF-8编码为bytes。含有中文的str无法用ASCII编码,因为中文编码已经超出ASCII编码的范围
len()函数计算的是str的字符数,如果换成bytes,len()函数就计算字节数
(b’ABC’)
3len(b’\xe4\xb8\xad\xe6\x96\x87’)
6len(“中文”.encoe(‘utf-8’)
6
一个中文字符经过UTF-8编码后通常占用3个字节,而一个英文字符只占用1个字节
##格式化
###占位符
据说是和c语言一样,可惜我学的是c++
常用占用符
%s 为str
%d 表示整数替换
%f 浮点数
%x 十六进制整数
如果只有一个%,括号可以省略
‘Hello,%s’%‘World’
‘Hello,World’‘Hi,%s,you have $%d.’ %(‘Michael’,10000000000000)
'Hi,Michael,you have $10000000000000000‘%2d-%02d’ %(3,1) #后面第一个是填充符没有就算了,第二个是宽度
’ 3-01’‘%.2f’ % 3.1415926
‘3.14’
#使用list和tuple
列表可以修改,而元组不可以修改
#列表方法
##list
Python 内置的一种数据类型是列表:list. list是一种有序的集合,可以随时添加和删除其中的元素。
such as :
##copy
a=[1,2,3,4]
b= a.copy()
##count计算指定元素在列表中出现的次数
【】
[42]*5
[42,42,42,42,42]
classmates=[‘DemoD_’,‘DemoLi_’,‘DemoFuture_’]
[‘DemoD_’,‘DemoLi_’,‘DemoFuture_’]len(classmates)
3classmates[0]
‘DemoD_’classmates[1]
‘DemoLi_’classmates[2]
‘DemoFuture_’classmates[-1]
‘DemoFuture_’classmates[-2]
‘DemoLi_’classmates[-3]
‘DemoD_’
#向classmates后面直接添加元素classmates.append(‘DemoEr_’)
classmates
[‘DemoD_’,‘DemoLi’,‘DemoFuture’,‘DemoEr’]
#向classmates固定位置添加元素classmates.insert(1,‘DemoC_’)
classmates
[‘DemoD_’,‘DemoC_’,‘DemoLi_’,‘DemoFuture_’,‘DemoEr’]
#删除末端的元素,并返回删掉的元素,pop()classmates.pop()
‘DemoEr’classmates
[‘DemoD_’,‘DemoC_’,‘DemoLi_’,‘DemoFuture_’]
#删除固定位置的元素,并返回删掉的元素,pop(i)classmates.pop(1)
‘DemoC_’classmates
[‘DemoD_’,‘DemoLi_’,‘DemoFuture_’]
#修改某个位置元素的valueclassmates[1]=‘DemoAi_’
classmates
[‘DemoD_’,‘DemoAi_’,‘DemoFuture_’]
##tuple(元组)
元组是一种有序列表:tuple。 tuple 和 list非常相似,但是 tuple 一旦初始化就不能修改了
such as :
classmates=(‘DemoD_’,‘DemoLi_’)
tuple 没有 append(),insert() ,pop()这样可以修改的函数
所以他安全hehe
###tuple的定义
t=(1,2)
t
(1,2)t=()
t
()t=(1) #t仅仅是 int 1
t
1t=(1,)
t #这个t 才是元组,一个元素的元组这么定义
(1,)
虽然说 **tuple**初始化不可变,但是他的元素如果有 list 类型的话,可以改变 list 的元素
**Look at the following code**
t=(‘Apple_’,‘Banana_’,[‘DemoD_’,‘DemoLi_’])
t[2][0]=‘DemoEr_’
t
(‘Apple_’,‘Banana_’,[‘DemoEr_’,‘DemoLi_’])
#条件判断
##条件判断
age=20
if age>=18:
print(‘your age is’,age)
print(‘adult’)
your age is 20
adult
emmm
else if = elif
age=3
if age>=18:
print(‘teenage’)
else:
print(‘infancy’)
infancy
#循环
##1.range(i) range(i,j)
for i in range(5):
print(i)
0
1
2
3
4for i in range(1,5):
print(i)
1
2
3
4s=[‘DemoD_’,‘DemoLi_’]
for i in s:
print(i)
‘DemoD_’
‘DemoLi_’
##while
sum = 0
n=100
while n>0:
sum+=n
n-=1print(sum)
5050
#使用dict和set
##dict {}
Python 内置字典:dict=dictionary 使用 key-value 存储
###突然忘记交互式死循环 ctrl+c 结束
1.Value查找
d={‘DemoD_’:100,‘DemoLi_’:90,‘DemoFu_’:80}
d
{‘DemoD_’:100,‘DemoLi_’:90,‘DemoFu_’:80}d[‘DemoD_’]
100
2.添加元素
d[‘DemoD_’]=67
d[‘DemoD_’]
67d.get(‘DemoD_’)
67
如果'DemoD_'存在,则Rush 'DemoD_'
为了避免key不存在,两种方法判断
(1):
‘DemoD_’ in d
False
(2)get() 如果key不能存在,返回None,也可以自定义返回“符号”
d={‘DemoD_’:100}
d.get(‘DemoLi_’)
d.get(‘DemoLi_’,-1)
-1d.get(‘DemoD_’)
100d.pop(‘DemoD_’)
100d
{}
###dict内部存放的顺序和key放入的顺序是没关系的
##set
set 和 dict 类似,也是一组 key 的集合 ,但是不存储 value。 由于 key 不能重复,所以,在 set中,没有重复的key.
###创建一个 set ,需要提供一个 list 作为输入集合
s = set([1,2,3])
s
{1,2,3}
**set**自动过滤重复元素
s=set([1,1,2,2,3,3])
s
{1,2,3}
**添加元素**add(key)
s=set([1,2,3])
s.add(4)
s
{1,2,3,4}
**删除元素**remove(key)
s.remove(4)
s
{1,2,3}
set 可作交集,并集等操作
s1=set([1,2,3])
s2=set([2,3,4])
s1 & s2
{2,3}s1 | s2
{1,2,3,4}
##调用函数
###abs
abs(100)
100abs(100)
100a=abs
a(-1)
1
###max
max(1,2)
2max(1,2,3)
3
#数据类型转换
int(‘123’)
123int(12.34)
12float(‘12.34’)
12.34str(1.23)
‘1.23’str(100)
‘100’bool(1)
Truebool(’’)
False
#定义函数
such as :my_abs
def my_abs(x):
if x>=0:
return x
else:
return -x
**return None = return**
#空函数
如果想定义一个什么也不干的空函数,可以用 pass 语句
such as : nop
def nop():
pass
**数据类型检查**
可以用内置函数 isinstance() 实现,只允许整数,浮点数类型的参数
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError(‘bad operand type’)
if x>=0:
return x
else:
return -x
#函数的参数
##位置参数
def power(x):
return x*x
参数 x 就是一个位置参数
def power(x,n):
s=1
while n>0:
n-=1
s=s*x
return s
参数 x , n 也是位置参数
##默认参数
def power(x ,n=2):
s=1
while n>0:
n-=1
s*=x
return s
power( 5) = power( 5, 2)
**必选参数放在前,默认参数在后,多个默认参数的话,吧变化大的参数放在前面,变化小的参数放到后面,变化小的参数就可以作为默认参数**
所以默认参数可以降低调用函数的难度--
##可变参数
参数的个数不确定
example:
def calc(number):
sum=0
for n in number:
sum=sum+nn
return sumcalc(1,2)
5cals()
0nums=[1,2,3]
calc(nums[0],nums[1],nums[2])
14calc(*nums) #上面的太麻烦so
14
##关键字参数
关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数,在函数内部自动组装为一个dict
e.g.
def person(name,age,**kw):
print(‘name:’,name,‘age:’,age,‘other:’,kwperson(‘DemoD_’,21)
name:DemoD_ age:21 other:{}person(‘DemoD_’,21,job=‘Student’,city=‘Shanxi’)
name:DemoD_ age:21 other:{‘job’:‘Student’:‘ShanXi’}
##参数组合
必选参数,默认参数,可变参数,关键字参数和命名关键字参数
可变参数和命名关键字参数无法混合
参数定义的顺序
必选参数 默认参数 可变参数/命名关键字参数 关键字参数
def f1(a,b,c=0,*args,**kw):
print(‘a=’,a,‘b=’,b,‘c=’,c,‘args=’,args,‘kw=’,kw)def f2(a,b,c=0,*,d,**kw):
print(‘a=’,a,‘b=’,b,‘c=’,c,‘d=’,d,'kw='kw) #的作用是后面的参数必须初始化f1(1,2)
a = 1 b = 2 c = 0 args = () kw ={}f1(1,2,3)
a = 1 b =2 c =3 args=() kw={}f1(1,2,3,‘a’,‘b’)
a=1 b=2 c=3 args=(‘a’,‘b’) kw={}f1(1,2,3,‘a’,‘b’,x=99)
a=1 b=2 c=3 args=(‘a’,‘b’) kw={‘x’:99}f2(1,2,d=99,ext=None)
a=1 b=2 c=0 d=99 kw={‘ext’:None}
#递归函数
在函数内部,调用自身本身,这个函数就是递归函数
n!
def fact(n):
if n==1:
return 1
return n*fact(n-1)fact(1)
1
###尾递归:return 返回值不包含自身函数,否则容易溢出
For instance
def fact(n):
return fact_iter(n,1)
def fact_iter(num,product):
if num==1;
return product
return fact_iter(num-1,num*product)
#切片
L=list(range(10))
L
[0,1,2,3,4,5,6,7,8,9]L[:10]
[0,1,2,3,4,5,6,7,8,9]L[-10:]
[0,1,2,3,4,5,6,7,8,9]L[2:4]
[3,4]L[1:10:2]
[1,3,5,7,9]L[::-1]
[9,8,7,6,5,4,3,2,1,0]L[:]
[0,1,2,3,4,5,6,7,8,9]
Tuple可以切片操作,但是操作的结果仍是Tuple
#迭代(diedai)(Iteration)
迭代:如果给定一个 List 或 tuple ,我们可以通过for循环来遍历这个list或tuple(for ... in ...)
dirc.values() dirc.items().
#生成器(generator)
L=[x*x for x in range(10)]
L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]g=(x*x for x in range(10))
next(g)
0next(g)
1next(g)
4next(g)
9
generator 创建,把列表 []改成() 打印 generator 只能用next()函数获得generator的下一个返回值
so:
for i in g:
print(n)
1
4
9
16
25
36
49
64
81
generator 和函数的执行流程不一样。generator 的函数,在每次调用 next() 的时候执行,遇到 yield 语句返回,再次执行时从上次返回的 yield 语句处继续执行。
def odd():
print(‘step1’)
yield (1)
print(‘step2’)
yield( 3)
print(‘step3’)
yield(5)o=odd()
next(o)
step1
1next(o)
step2
3next(o)
step3
5
#sorted
Python 内置函数 sorted
1.对 list进行排序
sorted([36,5,-12,10])
[-12, 5, 10, 36]
#Little test
class Student(object):
def init(self,name,score):
self.name=name
self.score=score
def print_score(self):
print("%s:%s"%(self.name,self.score))
bart =Student(“DemoD_”,21)
lisa=Student(“DemoLi_”,20)
bart.print_score()
DemoD_:21lisa.print_score()
DemoLi_:20
#类和实例
类 (Class)和 实例(Instance)
定义类:
class Student(object) #object 代表继承那个类,如果没有的话就写object
实例化:
DemoD_=Student()
def __init__(self,name,score):#__init__首参数永远是self,表示创建的实例本身