# -*- 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. centos7 安装kubernetes1.4

    192.168.251.9 master192.168.251.231 node 建议可以搭建etcd集群来做数据库存储,并搭建kube-dns,然后把k8s的日志落地到/var/log/kubern ...

  2. python大小写转换函数

    1.全部转换成大写:upper() 用法: str = 'marsggbo'     print str.upper() 结果:MARSGGBO 2.全部转换成小写:lower() 用法:str = ...

  3. The superclass “javax.servlet.http.HttpServlet" was not found on the Java Build Path错误

    1.异常信息 创建maven web项目时,出现 The superclass "javax.servlet.http.HttpServlet" was not found on ...

  4. vue监听滚动事件,实现滚动监听

    在vue中实现滚动监听和原生js无太大差异,下面是一个简单的demo,可在控制台查看结果 <!DOCTYPE html> <html lang="en"> ...

  5. python爬虫实战(二)--------千图网高清图

    相关代码已经修改调试----2017-3-21 实现:千图网上高清图片的爬取 程序运行20小时,爬取大约162000张图片,一共49G,存入百度云.链接:http://pan.baidu.com/s/ ...

  6. wireshark filter manualpage

    NAME wireshark-filter - Wireshark filter syntax and reference SYNOPSIS wireshark [other options] [ - ...

  7. 【Java进阶】——初识数据库连接池

    [简介] 数据库连接池:程序启动时建立足够的数据库连接,并将这些连接组成一个连接池,由程序动态地对池中的链接进行申请,使用,释放. 相比之前的程序连接,减少了数据库的打开关闭次数,从而减少了程序响应的 ...

  8. C++中的继承详解(3)作用域与重定义,赋值兼容规则

    作用域与同名隐藏 一样的,先上代码 1 class A 2 { 3 public: 4 int a_data; 5 void a() 6 { 7 cout << "A" ...

  9. cssreset

    /** * http://cssreset.com */html, body, div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, ...

  10. .NET Framework 4.7 安装

    我们打开.NET Framework下载界面: https://www.microsoft.com/net/download/framework 这时你会发现,我们能下载的.NET Framework ...