python入门基础代码
#查找index函数的帮助 help(str.index) #for循环和break语句 from math import sqrt for i in range(2,101): flag=1 k=int(sqrt(i)) for j in range(2,k 1): if i%j==0: flag=0 break if(flag): print i
#continue语句,满足条件跳出continue后面的语句 sumA=0 i=1 while i<=5: sumA =i i =1 if i==3:
continue
print 'i=%d,sum=%d'%(i,sumA) #循环中的else语句 k=5
for i in range(1,10): if k==3: break else: print i
#自定义函数/素材1-100间素数 from math import sqrt def isprime(x): if x==1: return False k=int(sqrt(x)) for j in range(2,k 1): if x%j==0: return False return True
for i in range(2,101): if isprime(i):
print idef f(x,y=True): #默认参数要放在参数列表的最后
'x and y both correct words or not' if y:
print x,'and y both correct' print x,'is Ok' f(68) f(68,False) #传递函数 def addme2me(x): return(x x) def self(f,y): print f(y)
self(addme2me,2.2) #lambda函数
my_add=lambda x,y:x y my_add(5,6) #数据获取与表示
f=open(r'E:\\360Downloads\\firstpro.txt','w') #新建一个文件 f.write('hello,world') #f为对象,write写入文件 f.close()
f=open(r'E:\\360Downloads\\firstpro.txt','r') #r代表读出 p1=f.read(5) #5代表读出的字节数 p2=f.read()
print p1,p2 f.close
f1=open(r'E:\\360Downloads\\companies.txt') cname=f1.readlines() for i in range(0,len(cname)): cname[i]=str(i 1) '' cname[i] f1.close
f2=open(r'E:\\360Downloads\\scompanies.txt','w') f2.writelines(cname) f2.close() #网络数据获取 import urllib
r=urllib.urlopen('http://z.cn/') html=r.read #序列
#标准类型运算符 'apple'<'banana' [1,2,3]!=[4,5,6]#值比较 atuple=('ba',126.4) btuple=atuple
btuple is not atuple#对象身份比较
('86.40'<'122.64') and ('apple'<'banana')#布尔运算
#序列类型运算符
week=['mondy','tuesday','wednesday','thursday','firday','satuday','sunday'] print
week[1],week[-2],'\\n',week[1:4],'\\n',week[:6],'\\n',week[::-1]#序列值的序号是从0开始到N-1或者从-1到N 'apple'*3
'ba' in ('ba','the boeingcompany') #序列类型转换工厂函数
list('hello,world')#将字符串转成列表
tuple('hello,world')#将字符串转成元组#字符串 s1='''hello 'a' ''b'' world!'''
s1 #三引号可以保持里面字符串的原貌 s2=r'd:\\python\\a.py' s2
ccode=['axp','ba','cat','csco','cvx']
cprice=['86.40','122.64','99.44','23.78','115.91'] for i in range(5):
print '%d%8s:%8s' %(i,ccode[i],cprice[i]) #%8s指的占8个