# -*- coding: utf-8 -*-
#自定义函数
'''
def functionname( parameters ):
"函数_文档字符串"
function_suite
return [expression]
''' def printme( str ):
"打印传入的字符串到标准显示设备上"
print str
return #函数调用
printme("我要调用用户自定义函数!");
printme("再次调用同一函数"); # 可写函数说明
def changeme( mylist ):
"修改传入的列表"
mylist.append([1,2,3,4]);
print "函数内取值: ", mylist
return # 调用changeme函数
mylist = [10,20,30];
changeme( mylist );
print "函数外取值: ", mylist #参数
def printme( str ):
"打印任何传入的字符串"
print str;
return; #调用printme函数
printme(); def printme( str ):
"打印任何传入的字符串"
print str;
return; #调用printme函数
printme( str = "My string"); def printinfo( name, age ):
"打印任何传入的字符串"
print "Name: ", name;
print "Age ", age;
return; #调用printinfo函数
printinfo( age=50, name="miki" ); def printinfo( name, age = 35 ):
"打印任何传入的字符串"
print "Name: ", name;
print "Age ", age;
return; #调用printinfo函数
printinfo( age=50, name="miki" );
printinfo( name="miki" ); #不定长参数
'''
def functionname([formal_args,] *var_args_tuple ):
"函数_文档字符串"
function_suite
return [expression]
'''
def printinfo( arg1, *vartuple ):
"打印任何传入的参数"
print "输出: "
print arg1
for var in vartuple:
print var
return; # 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 ); #匿名函数
'''
lambda [arg1 [,arg2,.....argn]]:expression
''' sum = lambda arg1, arg2: arg1 + arg2;
# 调用sum函数
print "相加后的值为 : ", sum( 10, 20 )
print "相加后的值为 : ", sum( 20, 20 ) #return语句
def sum( arg1, arg2 ):
# 返回2个参数的和."
total = arg1 + arg2
print "函数内 : ", total
return total; # 调用sum函数
total = sum( 10, 20 );
print "函数外 : ", total #变量的作用范围
total = 0; # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
#返回2个参数的和."
total = arg1 + arg2; # total在这里是局部变量.
print "函数内是局部变量 : ", total
return total; #调用sum函数
sum( 10, 20 );
print "函数外是全局变量 : ", total #键盘输入
str = raw_input("Please enter:");
print "你输入的内容是: ", str str = input("Please enter:");
print "你输入的内容是: ", str #打开与关闭文件
# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace # 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
fo.close() # 打开一个文件
fo = open("foo.txt", "wb")
fo.write( "www.runoob.com!\nVery good site!\n"); # 关闭打开的文件
fo.close() # 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str
# 关闭打开的文件
fo.close() # 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str # 查找当前位置
position = fo.tell();
print "当前文件位置 : ", position # 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close() import os # 重命名文件test1.txt到test2.txt。
os.rename( "test1.txt", "test2.txt" ) import os # 删除一个已经存在的文件test2.txt
os.remove("test2.txt") #异常处理
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close() try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully" try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data" try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data" def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument # Call above function here.
temp_convert("xyz"); #异常触发
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here... #自定义异常
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args

python基本语法-函数与异常的更多相关文章

  1. Python基础语法函数

    函数是什么 Python中的函数与数学中的函数不同,它不再只是公式,而是实实在在有着自己特定功能的代码.其实在潜移默化中我们已经有所接触了. 比如print()函数,range()函数,type()函 ...

  2. Python基本语法_函数属性 & 参数类型 & 偏函数的应用

    目录 目录 前言 软件环境 Python Module的程序入口 函数的属性 Python函数的创建 函数的参数 必备参数 缺省参数 命名参数 不定长参数 匿名参数 偏函数的应用 前言 Python除 ...

  3. python基础语法_10错误与异常

    Python有两种错误很容易辨认:语法错误和异常. 语法错误 Python 的语法错误或者称之为解析错,是初学者经常碰到的,如下实例 异常 即便Python程序的语法是正确的,在运行它的时候,也有可能 ...

  4. python学习第五讲,python基础语法之函数语法,与Import导入模块.

    目录 python学习第五讲,python基础语法之函数语法,与Import导入模块. 一丶函数简介 1.函数语法定义 2.函数的调用 3.函数的文档注释 4.函数的参数 5.函数的形参跟实参 6.函 ...

  5. python基础语法20 面向对象5 exec内置函数的补充,元类,属性查找顺序

    exec内置函数的补充 exec: 是一个python内置函数,可以将字符串的代码添加到名称空间中; - 全局名称空间 - 局部名称空间 exec(字符串形式的代码, 全局名称空间, 局部名称空间) ...

  6. Python基本语法[二],python入门到精通[四]

    在上一篇博客Python基本语法,python入门到精通[二]已经为大家简单介绍了一下python的基本语法,上一篇博客的基本语法只是一个预览版的,目的是让大家对python的基本语法有个大概的了解. ...

  7. Python 基础语法(三)

    Python 基础语法(三) --------------------------------------------接 Python 基础语法(二)------------------------- ...

  8. Python基础:函数

    一.概述 二.声明.定义和调用 三.参数 1.参数传递 2.实参类型 3.形参绑定 四.返回值 五.名字空间与作用域 1.基本概念 2.名字空间 3.作用域 4.总原则 六.高级 1.装饰器 2.生成 ...

  9. Python 基础语法(四)

    Python 基础语法(四) --------------------------------------------接 Python 基础语法(三)------------------------- ...

随机推荐

  1. ZooKeeper集群-搭建指南

    第一步: 上传安装程序到Linux 这一步很简单就不在这过多说明了! 第二步: 在Linux上使用命令行安装 第三步: 修改配置文件 1.修改zoo.cfg文件 2.修改集群中各台主机的名称 1).如 ...

  2. SVG动画-基础篇

    参考资料: http://www.w3school.com.cn/svg/index.asp https://msdn.microsoft.com/zh-cn/library/gg193979 简介 ...

  3. ng自定义服务(利用factory)

    ng中我们可以自己定义自己的服务,服务中是一些使用重复率较高的方法.因此有效的使用服务可以提高开发速度. ng中定义服务的方法有多种,service,factory,provide,在此我只介绍最长用 ...

  4. 老李分享:《Linux Shell脚本攻略》 要点(七)

    老李分享:<Linux Shell脚本攻略> 要点(七)   1.显示给定文件夹下的文件的磁盘适用情况 [root@localhost program_test]# du -a -h ./ ...

  5. 玩转SSH(四):Struts + Spring + MyBatis

    一.创建 SSMDemo 项目 点击菜单,选择“File -> New Project” 创建新项目.选择使用 archetype 中的 maven-webapp 模版创建. 输入对应的项目坐标 ...

  6. 利用原生JS判断组合键

    <script type="text/javascript"> var isAlt = 0; var isEnt = 0; document.onkeydown = f ...

  7. druid查询

    查询是发送HTTP请求到,Broker, Historical或者Realtime节点.查询的JSON表达和每种节点类型公开相同的查询接口. Queries are made using an HTT ...

  8. 树状数组 && 线段树

    树状数组 支持单点修改 #include <cstdio> using namespace std; int n, m; ], c[]; int lowbit(int x) { retur ...

  9. CHM文件无法打开或无法搜索

    在确保CHM文件本身正常的前提下,检查c:\\windows\hh.exe和C:\\windows\system32\itss.dll和hhctrl.ocx三个文件是否存在. 如不存在,只需要从其他机 ...

  10. mysql数据库实操笔记20170418

    一.建立商品分类表和价格表: 1.分类表`sankeq``sankeq`CREATE TABLE cs_mysql11(id INT(11) NOT NULL AUTO_INCREMENT,categ ...