python的一些常见用法

1.字典

创建:

dict={};

添加元素:

dict[‘1’]=‘a’;

遍历:

for index in dict:

print index,dict[dict]

#结果输出为 1,'a'

删除:

del dict[‘1’]

#结果'1':'a'这一对key/value都被删除了。不过注意,不能在遍历字典的时候使用del。一种方法是遍历的时候先保存欲删除的index,然后再统一删除。


2.检查文件/目录是否存在

import os
file_name=r'D:/hello/1'
if os.path.exists(file_name):
    print "exit"
else:
    print "not exit"


3.range()函数

>>> range ( 1 , 5 ) #代表从1到5(不包含5)
[ 1 , 2 , 3 , 4 ]
>>> range ( 1 , 5 , 2 ) #代表从1到5,间隔2(不包含5)
[ 1 , 3 ]
>>> range ( 5 ) #代表从0到5(不包含5)
[ 0 , 1 , 2 , 3 , 4 ]

4.python的try和catch用法示例

(参考http://blog.csdn.net/spch2008/article/details/9343207)

第一: try不仅捕获异常,而且会恢复执行

1.  def catcher():  

2.      try:  

3.          fetcher(x, 4)  

4.      except:  

5.          print "got exception"  

6.      print "continuing"  

输出:

1.  got exception  

2.  continuing  


第二:无论try是否发生异常,finally总会执行

1.   

2.  def catcher():  

3.      try:  

4.          fetcher(x, 4)  

5.      finally:  

6.          print 'after fecth'  

输出:

1.  after fecth  

2.  Traceback (most recent call last):  

3.    File "test.py", line 55, in <module>  

4.      catcher()  

5.    File "test.py", line 12, in catcher  

6.      fetcher(x, 4)  

7.    File "test.py", line 4, in fetcher  

8.      return obj[index]  

9.  IndexError: string index out of range  


第三:try无异常,才会执行else

1.  def catcher():  

2.      try:  

3.          fetcher(x, 4)  

4.      except:  

5.          print "got exception"  

6.      else:  

7.          print "not exception"  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值