python基础的语句及用法

1.python编译
$ vim 1.py
#!/usr/bin/python //(可以实现直接运行)
print 'hello world'

$ chmod +x 1.py
$ ./1.py


$ vim 2.py
import py_compile
py_compile.compile('1.py') //(将1.py编译为可执行文件)

$ python 2.py //生成1.pyc文件

$ python -O -m py_compile 1.py //生成1.pyo文件。为优化的可执行文件


2.python变量
3.python运算
#!/usr/bin/python
a = raw_input() //从键盘获取输入的数
b = int(raw_input()) //类型转换
c = int(raw_input(“请输入一个整数”))
print a+b
4.python数据类型

数字,字符串,列表,元组,字典
type(num1)
4.1序列
4.1.1字符串的索引
例如 a='abcde'
a[起始:结束:步长]
a[1:4] //bcd
a[-4:-1] //bcd
a[::] //abcde
a[::2] //取全部,步长为2;得到ace
a[-2:-4:-1] //cb
4.1.2 序列操作
1. len() 求序列的长度 // len(str1)
2. + 连接两个序列 // str1 + str2
3. * 重复序列元素 // str1 * 5 重复5次
4. in 判断元素是否在序列中 // 'c' in str1 返回布尔值
5. max() 返回最大的值 // str2 = '12345' max(str2) 返回5
6. min() 返回最小的值
7. cmp(tuple1, tuple2) 比较两个的序列的值是否相同
// cmp(str1,str2) str1小于str2返回-1,大于1,等于0

4.1.3 元组
定义: t=("milo",30,"male") //t[0] t[1] t[2]
创建元组
空元组 myempty = ()
含有单个元素的元组 singleton=(2,)
一般的元组 zoo = ('wolf','elephant','penguin')
new_zoo = ('monkey','dolphin',zoo)
元组赋值
第一种:
>>> t=("milo",30,"male")
>>>name,age,gender=t
>>>name
'milo'
>>>age
30
第二种:
>>>a,b,c=(1,2,3)

4.1.4 序列--列表
定义一个列表:
>>>listmilo=[]
>>>type(listmilo)
<type 'list'>
>>>listmilo=['milo',30,'male']
>>>t=("milo",30,"male")
---------------------------------------------
>>>t[0]
'milo'
>>>listmilo[0]
'milo'
>>>t[0:2]
('milo',30)
>>>listmilo[0:3]
['milo',30,'male']
---------------------------------------------
修改 列表具体的元素值
元组具体的值不可被改变,而列表可以
>>>lista=["123",10,30]
>>>id(lista)
140689485588 528
>>>lista[1]=20
>>>lista
["123",20,30]
>>>id(lista)
140689485588 528
存储空间 不改变

元组改变某个值 只能全部一起改变但空间改变
>>>t=("123",10,20)
>>>id(t)
140689485657 264
>>>t[1]
10
>>>t[1]=20
出错
>>>t=("123",20,20)
>>>id(t)
140689485657 824
存储空间 改变
--------------------------------------------------------
增加 列表具体的元素值append
>>>listb=[20,30,40]
>>>listb.append(50)
>>>listb
[20,30,40,50]
>>>help(list.append)
删除 列表具体的元素值remove
>>>listb.remove(50) 或者 listb.remove(listb[2]) 或者 del(listb[2])
>>>listb
[20,30,40]
>>>help(list.remove)
查看 列表具体的元素值in
>>>20 in listb
Ture

4.2 字典
直接生成字典:
>>>dic={0:0,1:1,2:2}
>>>dic[0] //key
0 //value
>>>dic1={'name':'milo','age':30,'gender':'male'}
>>>dic1['name']
'milo'
工厂方法生成字典:
fdict=dict(['x',1],['y',2]) //效率低一般不使用
內建方式:fromkeys(),字典中有相同的值,默认为None
ddict={}.fromkeys(('x','y'),-1)

访问字典的值
>>>for k in dic:
... print k
...
gender
age
name
>>>for k in dic:
... dic[k]
...
'male'
30
'milo'
-----------------------------------------------------------------------
增加 字典具体的元素值
>>>dic
{'gender':'male','age':30,'name':'milo'}
>>>dic['tel']='12345678'
>>>dic
{'gender':'male','age':30,'tel':'12345678','name':'milo'}
修改 字典具体的元素值
>>>dic['age']=25
删除和更新 字典具体的元素值
>>>dic.update() 内容拷贝到另一个字典
>>>del dic['a']删除字典中 为a的元素
dic.pop('a')删除并返回键为‘a’的元素
dic.clear()删除字典所有元素
del dic删除整个字典
>>>help(dict.keys)

5 python流程控制
if 条件表达式:
执行代码 //建议 使用4个空格代替缩进

例如:
#!/usr/bin/python
def fun():
return 1

if fun():
print "ok"
-------------------------------------------------------------------------------
if 条件表达式1:
代码一
else:
代码二
--------------------------------------------------------------------------------
if 条件表达式1:
code1
elseif 条件表达式2:
code2
elseif 条件表达式3:
code2
else:
code3
--------------------------------------------------------------------------------
if嵌套
if x>=80:
if y>=90:
print "A"
elseif x<80:
print "B"
----------------------------------------------------------------------------------
使用与或非 and or not

6 for循环
for x in [0,1,2,3,4,5,6]
print x,"hello world"

range(i,j,[,步长值]) //其中i为初始值,j为终止值
num = 0
for x in range(10)
num += x

s="hello"
for x in range(len(s)):
print s[x]

遍历字典
d={1:111,2:222,3:333,5:555}

for x in d:
print x //获取的是key
print d[x]

print d.items() //[(1,111),(2,222),(3,333),(5,555)]

for k,v in d.items():
print k
print v
else:
print "ending" //for循环非正常结束输出"ending"

import time
for x in range(300):
print x
if x == 222:
exit()
if x == 3:
pass
if x == 2
print "hello 22222"
continue
if x == 200:
break
else:
print "ending"

7 while循环
x = ""
while x != "q": //x为q结束,由ending
print "hello"
x = raw_input("please input something,q for quit:")
if not x: //x为空结束,没有ending
break
if x == "c":
continue
print "one more time~~~"
else:
print "ending........"

8 函数
#!/usr/bin/python
#coding:utf8
def 函数明(形参*):
函数体
----------------------------------------
def fun():
if False:
print "good"
print a

if fun():
print "ok"
--------------------------------------
可设置参数默认值
1.
def machine(x=3,y="巧克力"):
print ‘生成一个’,x,‘元’,y,‘口味的冰激凌!’

machine() //给了默认值可不传参数
machine(5) //生成一个 5 元 巧克力 口味的冰激凌!
machine('奶油') //生成一个 奶油 元 巧克力 口味的冰激凌!
machine(y='奶油')
2.
def machine(x=3,y): //错误, 默认参数设置应从右向左
print ‘生成一个’,x,‘元’,y,‘口味的冰激凌!’

machine('巧克力') 错误
------------------------------------------------
global语句,将函数内局部变量 强制声明为全局变量,注意 函数需要被调用
1.
y = 100
def fun():
x=100
global y
y=200
fun()
print y //200
--------------------------------------------------
元组传参
t=('name','milo')
def f(x,y)
print "%s : %s" % (x,y)
f( * t)
字典传参
d={'age':30,'name':'milo'}
def f(name,age):
print 'name : %s' % name
print 'age : %s' % age
f( ** d)
f(d['name'],d['age'])
---------------------------------------------------
处理多余参数
>>>def f(x,*args):
... print x
... print args
>>>f(1,2,3)
1
(2,3)
---------------------------------------------------
lambda表达式
匿名函数
def f(x,y):
return x*y
f(2,3)

g=lambda x,y:x*y //与es6中箭头函数类似
g(2,3)

reduce方法
>>>l = range(1,6)
>>>f = lambda x,y:x*y
>>>reduce(f,l)
120
可一行解决
reduce(lambda x,y:x*y ,l)

9 switch
通过函数实现
#!/usr/bin/python
#coding:utf-8

from __future__ import division

def jia(x,y):
return x+y
def jian(x,y):
return x-y
def cheng(x,y):
return x*y
def chu(x,y):
return x/y

operator = {"+":jia,"-":jian,"*":cheng,"/":chu}

def f(x,o,y):
print operator.get(o)(x,y,*args,**kwargs)

f(3,"+",2)

通过字典调用函数
{1:case1,2:case2}.get(x,lambda *arg,**key:)()

使用字典实现switch语句
from __future__ import division
x=1
y=2
operator = "/"
result = {
"+":x+y
"-":x-y
"*":x*y
"/":x/y
}
print result.get(operator)

10 内置函数
abs()
max()
min()
len()
divmod() div(5,2)得到(2,1)
pow() pow(2,3)得到8 pow(2,3,4)==>8%4=0
round()
------------
callable() 判断某个函数是否可调用
isinstance()
cmp()
range()
xrange()
-----------
type()
int()
long()
float()
complex()
str()
list()
tuple()
hex()
oct()
chr()
ord()

string函数
str.capitalize() //首字母大写
str.replace() //字符串替换
s.replace("hello","hi") 全替换
s.replace("hello","hi",3)将hello替换为hi替换3次
str.split() str.split([sep,[,maxsplit]]) 拆分后得到列表
-------------------------------------------------------------------------------------------------
还可使用导入模块的方式
import string
string.replace(str,old,new,[,count])

序列处理函数
filter()
>>>def f(x):
... if x>5:
... return True
>>>l = range(10)
>>>filter(f,l)
[6,7,8,9]

zip()
map()
>>>name=['milo','zou','tom']
>>>age=[20,30,40]
>>>tel=['133','156','189']
>>>zip(name,age,tel)
[('milo',20,133),('zou',30,156),('tom',40,189)]
>>>map(None,name,age,tel)
[('milo',20,133),('zou',30,156),('tom',40,189)]
区别如下
1.
>>>test=[1,2]
>>>zip(name,age,tel,test)
[('milo',20,133,1),('zou',30,156,2)]
>>>map(name,age,tel,test)
[('milo',20,133,1),('zou',30,156,2),('tom',40,189,None)]
2.
>>>a=[1,3,5]
>>>b=[2,4,6]
>>>def mf(x,y):
... return x*y
>>>map(mf,a,b)
[2,12,30]

reduce()
reduce(function,sequence[,initial])
reduce(lambda x,y:x+y,[1,2,3,4,5])计算过程((1+2)+3)....

11 模块module
创建一个.py文件可作为模块在另一个.py文件中调用。
例如调用cal.py
import cal
import cal as newname
from cal import jia
cal.jia(1,2)

12 正则表达式
13 浅拷贝和深拷贝
import copy
c=copy.copy(a)
d=copy.deepcopy(a)
浅拷贝未分配独立的内存空间

14 文件的读写
1.
fnew=file_obj.open('路径','模式')
fnew.read()
fnew.write('内容')
fnew.close()
2.
with open('文件路径','r+') as file_obj:
contents = file_obj.read()
file_obj.write('内容')
print(contents.rstrip())

逐行打印
>>>for i in open('test.txt')
readline()
>>>f1.open('test.txt')
>>>f1.readline()
'aaaaaaaaaaaaaa\n'
>>>f1.readline()
'bbbbbbbbbbbbbb\n'
readlines()
>>>f1.open('test.txt')
>>>f1.readlines()
['aaaaaaaaaaaaaa\n','bbbbbbbbbbbbbb\n']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值