第一个例子
#打开新窗口,输入: #! /usr/bin/python # -*- coding: utf8 -*- s1=input("Input your name:") print("你好,%s" % s1) ''' 知识点: * input("某字符串")函数:显示"某字符串",并等待用户输入. * print()函数:如何打印. * 如何应用中文 * 如何用多行注释 '''
注意,当使用input函数,输入字符串时,需要使用""将字符串包含起来,否则会报错如下
Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> input_A = input("Input: ") File "<string>", line 1, in <module> NameError: name 'abc' is not defined
第二个例子
#! /usr/bin/python x={'a':'aaa','b':'bbb','c':12} print (x['a']) print (x['b']) print (x['c']) for key in x: print ("Key is %s and value is %s" % (key,x[key])) ''' 知识点: * 将他当Java的Map来用即可. '''
第三个例子
#! /usr/bin/python word="abcdefg" a=word[2] print ("a is: "+a) b=word[1:3] print ("b is: "+b) # index 1 and 2 elements of word. c=word[:2] print ("c is: "+c) # index 0 and 1 elements of word. d=word[0:] print ("d is: "+d) # All elements of word. e=word[:2]+word[2:] print ("e is: "+e) # All elements of word. f=word[-1] print ("f is: "+f) # The last elements of word. g=word[-4:-2] print ("g is: "+g) # index 3 and 4 elements of word. h=word[-2:] print ("h is: "+h) # The last two elements. i=word[:-2]
print ("i is: "+i) # Everything except the last two charactersz
l=len(word)
print ("Length of word:" + str(l))
条件循环语句
#!/usr/bin/python #条件和循环语句 x=int(input("Please enter an integer:")) if x<0: x=0 print ("Negative changed to zero") elif x==0: print ("Zero") else: print ("More") # Loops List a = ['cat', 'window', 'defenestrate'] for x in a: print (x, len(x)) #知识点: # * 条件和循环语句 # * 如何得到控制台输入
函数
#! /usr/bin/python # -*- coding: utf8 -*- def sum(a,b): return a+b func = sum r = func(5,6) print (r) # 提供默认值 def add(a,b=2): return a+b r=add(1) print (r) r=add(1,5) print (r)
#返回空,和判断函数返回值是否为空
def voidfunc():
return None
ret = voidfunc()
if ret is None:
print 'this function return nothing'
一个好用的函数
#! /usr/bin/python # -*- coding: utf8 -*- # The range() function a =range (1,10) for i in a: print (i) a = range(-2,-11,-3) # The 3rd parameter stands for step for i in a: print (i)
异常处理
#!/usr/bin/python s=input("Input your age:") if s =="": raise Exception("Input must no be empty.") try: i=int(s) except Exception as err: print(err) finally: # Clean up action print("Goodbye!")
注意:老版本的Python,except语句写作"except Exception, e",Python 2.6后应写作"except Exception as e"。
返回值
对于python执行程序完成后,我们需要给程序一个返回值。设置方法如下。
#!/usr/bin/python import sys sys.exit(0) #如果想要检查一个python的返回值,可以如下 import os ret = os.system('./example.py') print(ret)
ConfigParser的使用
#!/usr/bin/env python import ConfigParser import sys config=ConfigParser.ConfigParser() config.add_section("book1") config.set("book1","title","hello world") config.set("book1","aut","log") config.write(open("f.txt","w"))
config.read("f.txt")
s = config.sections()
print 'section:', s
titile = config.get("book1", "title")
''' f.txt内容 [book1] aut = log title = hello world '''
python main解析
#!/usr/bin/env python
#文件名为main.py def main(): print "main function runing" if __name__ == "__main__": main()
如果在另一个文件中作为模块调用
#!/usr/bin/env python #如果有 if __name__ = "__main__": 语句,则无任何打印结果 #反之,则会正常执行main.py import main
定义自己的模块
在Python中,每个Python文件都可以作为一个模块,模块的名字就是文件的名字。
#test.py def display(): print 'hello world' display() #调用模块内容 #test1.py import test
urllib.unquote(string) :对字符串进行解码;
data = 'name = ~a+3' data1 = urllib.quote(data) print data1 # result: name%20%3D%20%7Ea%2B3 print urllib.unquote(data1) # result: name = ~a+3 data2 = urllib.quote_plus(data) print data2 # result: name+%3D+%7Ea%2B3 print urllib.unquote_plus(data2) # result: name = ~a+3 data3 = urllib.urlencode({ 'name': 'dark-bull', 'age': 200 }) print data3 # result: age=200&name=dark-bull data4 = urllib.pathname2url(r'd:ac23.php') print data4 # result: ///D|/a/b/c/23.php print urllib.url2pathname(data4) # result: D:ac23.php
urlparse 拆分网址为 RFC 中对应的组件。
from urlparse import urlparse url = ’http://netloc/path;param?query=arg#frag’ parsed = urlparse(url) print parsed ''' 执行结果: $ python urlparse_urlparse.py ParseResult(scheme=’http’, netloc=’netloc’, path=’/path’, params=’param’, query=’query=arg’, fragment=’frag’) '''
按行读取文件
# File: readline-example-1.py file = open("sample.txt") while 1: line = file.readline() if not line: break pass # do something # File: readline-example-2.py import fileinput for line in fileinput.input("sample.txt"): pass # 带缓存 # File: readline-example-3.py file = open("sample.txt") while 1: lines = file.readlines(100000) if not lines: break for line in lines: pass # do something #python 2.2以后可以 # File: readline-example-5.py file = open("sample.txt") for line in file: pass # do something # 而在 python 2.1里面 只能使用如下方法 # File: readline-example-4.py file = open("sample.txt") for line in file.xreadlines(): pass # do something
字典dict, 列表, 元组,
''' 字典:dic={'a':12,'b':34} 列表:list=[1,2,3,4] 元组:tup=(1,2,3,4) ''' #字典操作 dict = {} dict['name'] = 'poseidon' # 注意如果使用下行命令读取,会报错 KeyError: 'form_submit' #print dict['name'] #读取方式应该为, noname为默认值 dict.get('name', 'noname')
#得到最后一个值
last = dict.pop()
#也可以得到第一个值
first = dict.pop(1)
列表
list[] = ["apple", "banana", "grape", "orange"] print list[0]
list[] = ["apple", "banana", "grape", "orange"] print list[0] #列表求交集 b1=[1,2,3] b2=[2,3,4] b3 = [val for val in b1 if val in b2] print b3 #列表就差集 b3 = [val for val in b1 if val not in b2] print b3 #列表排重对rows rows=list(set(rows))#排重列表