#【py脚本文件、基本输出格式】

#!/usr/bin/env python
print 'Hello word!'

if Ture:
  print 'if test1'
  print 'if test2'
  
aa=123
bb='123'
print type(aa)
print type(bb)

'''注释'''
print '''aaa
bbb
ccc
'''

print "He said 'hi!' "

变量(直接写字符):字母、下划线、数字 ; 区分大小写 ;

------------------------------------------------------------------------------
#【模块导入】

>>> import module,sys
>>> import test.py

>>> from module import funname
>>> from os import system

>>> import module as newname


import sys
import readline
readline.parse and bind('tab: complete')

>>> OS.<tab>
>>> sys.path
>>> sys.system('df')
------------------------------------------------------------------------------
#【获取输入输出、流程控制】

for i info range(3):
	name = raw_input('What is your name?').strip() #获取控制台输入
	if len(name) == 0:
		continue
	else:
		break

while ture:		
	name = raw_input('What is your name?').strip()
	if len(name) == 0:
		continue
	else:
		break
		
		
age = int(raw_input('What is your age?')) #类型转换
sex = raw_input('What is your sex?').strip() 
job = raw_input('What is your job?')

print """Personal info:
	name:  %s
	age :  %d
	sex :  %s
	job :  %s
""" % (name,age,sex,job)

print "Your name is %s , it's a good name." % name  #变量输出

if age < 28:
	print "aaaaaaaaaa"
elif age ==28:
	print "bbbbbbbbbb"
else:
	print "cccccccccc"
	
------------------------------------------------------------------------------
#【文件读写】

f = file('user.txt','w') #新建文件
f.write('kk 123456')
f.close()

os.system('ls')

a = file('user.txt','a') #附加到文件
a.write('\n')
a.write('mm 123456')
a.read() #顺序逐行读
a.close()

#按字节读所有
for line in a.read():print line
#按行读所以
for line in a.readlines():print line

----------------------
#【列表】

names = ['aa','bb','cc]

names
names[0]
names[1]
names[2]

for line in a.readlines():print line[0] #行的字符位置

#字符串转列表
l = 'user pwd'
l.split()
l.split('e')

a = file('lock.txt') 
for line in a.readlines():print line[0], #每行的字符位置

for line in a.readlines():print line.split(), #转为数组

for line in a.readlines():print line.split()[1], #转数组取第二列

------------------------------------------------------------------------------
#登录验证:

#!/usr/bin/env python

account_file = 'account.txt'
lock_file = 'lock.txt'

for i in range(3):
	username = raw_input("username:").strip()
	password = raw_input("password:").strip()
	if len(username) !=0 and len(password) !=0:
		f = file(account_file)
		loginSuccess = False
		for line in f.readlines():
			line = line.split()
			if username == line[0] and password == line[1]:
				print "Welcome %s login my system" % username
				loginSuccess = True
				break
		if loginSuccess is True:
			break
	else:
		continue
else:
	f = file(lock_file,'a')
	f.write('%s\n' %username)
	f.close()

------------------------------------------------------------------------------
#【文件处理】
#创建文件(w、r、a、w+、r+、wb、rb)
f = file('myfile.txt','w')
f.write("Helloword!")
f.close

#遍历文件内容
a = file('myfile')
for line in a.readlines():
	print line,
a.close

#追加
f = file('myfile.txt','a')
f.write("append to end")
f.close

------------------------------
import time

f = file('test.txt','a')

for i in range(10,20):
	time.sleep(1)
	f.write('the %s loops\n' % i)
	f.flush()

f.close()

------------------------------
import fileinput

for line in fileinput.input('test.txt',inplace=1):
	line = line .replace("aaa","bbb")
	print line,

	
for line in fileinput.input('test.txt',inplace=1,backup='.bak'):
	line = line .replace("aaa","bbb")
	print line,

------------------------------------------------------------------------------
#【列表】(有序)
name_list = ['aaa','bbb','ccc']
l = [x for x in range(100)]

for i in range(10): name_list.append(i)

name_list.index('ccc')

name_list.insert(4,'ddd')

name_list.count('ddd')
name_list.remove('ddd')

name_list.pop()
name_list.pop(2)
name_list.reverse()
name_list.sort()
name_list.extend([99,100,'kk'])
name_list.extend('ABC') $分解每个字符添加

name_list[2] = 'CCC'

name_list[2:6] #部分列表
name_list[10:]
name_list[:-5]

name_list[1::2]

a = [1,2,3,4]
b = [2,4,6,8]

a + b
zip(a,b)

for i,v in zip(a,b):
	print i,v


c = []
for i in range(10):
		c.append(i*i)
	
c = [ i*i for i in range(10)]
	
	
#【元祖】不可更改,操作类似数组
d = (1,2,3,4,5,6)

d.count()
d.index()

----------------------------
#【字典】无序
contacts = {
	'kk' : 13900001111,
	'mm' : [13500002222,'student',25],
	'gg' : {'age': 28},
}

contacts['kk'] = 123456789	#修改
del contacts['kk']  #删除
contacts['kk hi'] = 123456789 #添加

contacts.get('mm')

#键打印
for i in  contacts:
	print i

#按元祖打印	
for i in  contacts.items():
	print i

#键值打印
for k,v in  contacts.items():
	print k,v

	
contacts.keys()   #查看键
contacts.values() #查看值
contacts.popitem() #删除第一个

if contacts.has_key('kk'): print contacts['kk']

for i in contacts: print i,i.count('K')

----------------------------

contact_dic = {}
with open('contacts_file.txt') as f:
	for i in f.readlines():
		line = i.strip().split()
		contact_dic[line[0]] = line[1:]
		
print contact_dic.keys()


if contact_dic.has_key('kk'):
	print ...
else:
	for name,value in contact_dic.items():
		if 'kk' in value:
			print ...
		else:
			print 'no valid record.'
		
------------------------------------------------------------------------------
#【函数】
---------------------------
#!/usr/bin/enc python

df_name = 'kk'
def printmsg2(name=df_name):
	global ads
	ads = "pppppppp"
	print "Hello,%s." % name

printmsg2()
printmsg2("mm")
print ads

---------------------------
#!/usr/bin/enc python

def func1(a,b=5,c=10):
	print "a is ",a," and b is ",b , " and c is ",c

func1(3,7)
func1(25,c=24)
func1(c=50,a=100)
---------------------------
#!/usr/bin/enc python

def func1(x,y):
        if x > y:
                return x
        else:
                return 100

if func1(1,2)==100:
        print "11111111"
else:
        print "22222222"

------------------------------------------------------------------------------
#【集合】

a = [1,4,2,5,4,36,5,4]
a = set(a) #列表去重
b = set([5,4,6,3,5])

a & b  #交集
a.intersection(b)  #交集

a | b  #并集
a.union(b)

a - b,b - a  #差集
a ^ b #对称差集(左右差集总和)


------------------------------------------------------------------------------
#【迭代器】
a = [1,2,3,4,5]
b = iter(a)

for i in b: print(i)

#【lambda】(匿名/简单函数)

a = lambda x:x**2
a(3)

a = lambda i,j:i+j
a(3,10)


lambda x:x**2,5

d = map(lambda x:x**2, [i for i in range(10)])

------------------------------------------------------------------------------
#【pickle 序列化】

import pickle

account_info = {
'123456':['kk',15000,15000],
'123457':['mm',9000,9000],
}

f = file('account.pkl','wb')
pickle.dump(account_info,f)
f.close()

---------------------
#保持为文件
#!/usr/bin/env python

import pickle

name_list = {
	'kk':[29,'IT'],
	'rain':{
		'age': 24,
		'job': 'salse',
	},
	'jack': 999
}

f = file('name_list.pkl','wb')
pickle.dump(name_list,f)
f.close()

---------------------
#读取文件
import pickle
f  = file('name_list.pkl')
#f.readlines()
name_list = pickle.load(f)
name_list['kk']
name_list['rain']['age']

------------------------------------------------------------------------------
#【Json】

import json
import pickle
f  = file('name_list.pkl')
name_list = pickle.load(f)
json.dumps(name_list)


f  = file('name_list.json')
json.load(f)
------------------------------------------------------------------------------
#【正则表达式】

import re
p = re.compile('hello')
m = p.match('hello world')

p.findall('hello worldhello worldhello world')

------------------------------------------------------------------------------
#【模块】
import sys
import os

r = os.popen('ls')
r.readlines()

for line in os.popen('df').readlines(): print line,

for line in os.popen('dir').readlines(): print (line)

import commands
commands.getoutpout('df')

status,results = commands.getoutpout('df')

------------------------------
#!/usr/bin/env python

aa = 'kk'
pi = 3.14

def tellName():
	print "hello world"

if __name__ == '__main__':
	tellName()

------------------------------------------------------------------------------
#【异常处理】

try:
	int(raw_input("Please inout your age:"))
except ValueError:
	print "You must input an interger."

------------------------------------------------------------------------------


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐