python基本语法-函数与异常
# -*- 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基本语法-函数与异常的更多相关文章
- Python基础语法函数
函数是什么 Python中的函数与数学中的函数不同,它不再只是公式,而是实实在在有着自己特定功能的代码.其实在潜移默化中我们已经有所接触了. 比如print()函数,range()函数,type()函 ...
- Python基本语法_函数属性 & 参数类型 & 偏函数的应用
目录 目录 前言 软件环境 Python Module的程序入口 函数的属性 Python函数的创建 函数的参数 必备参数 缺省参数 命名参数 不定长参数 匿名参数 偏函数的应用 前言 Python除 ...
- python基础语法_10错误与异常
Python有两种错误很容易辨认:语法错误和异常. 语法错误 Python 的语法错误或者称之为解析错,是初学者经常碰到的,如下实例 异常 即便Python程序的语法是正确的,在运行它的时候,也有可能 ...
- python学习第五讲,python基础语法之函数语法,与Import导入模块.
目录 python学习第五讲,python基础语法之函数语法,与Import导入模块. 一丶函数简介 1.函数语法定义 2.函数的调用 3.函数的文档注释 4.函数的参数 5.函数的形参跟实参 6.函 ...
- python基础语法20 面向对象5 exec内置函数的补充,元类,属性查找顺序
exec内置函数的补充 exec: 是一个python内置函数,可以将字符串的代码添加到名称空间中; - 全局名称空间 - 局部名称空间 exec(字符串形式的代码, 全局名称空间, 局部名称空间) ...
- Python基本语法[二],python入门到精通[四]
在上一篇博客Python基本语法,python入门到精通[二]已经为大家简单介绍了一下python的基本语法,上一篇博客的基本语法只是一个预览版的,目的是让大家对python的基本语法有个大概的了解. ...
- Python 基础语法(三)
Python 基础语法(三) --------------------------------------------接 Python 基础语法(二)------------------------- ...
- Python基础:函数
一.概述 二.声明.定义和调用 三.参数 1.参数传递 2.实参类型 3.形参绑定 四.返回值 五.名字空间与作用域 1.基本概念 2.名字空间 3.作用域 4.总原则 六.高级 1.装饰器 2.生成 ...
- Python 基础语法(四)
Python 基础语法(四) --------------------------------------------接 Python 基础语法(三)------------------------- ...
随机推荐
- Docker remote API简单配置使用
1.启动docker remote API的方式如下: docker -d -H uninx:///var/run/docker.sock -H tcp://0.0.0.0:5678 2.但是为了伴随 ...
- 组件之间使用Prop传递数据
<div id="example"> <father></father> </div> <script src="h ...
- java的特点跨平台原理以及JDK的安装
终于开始了期待已久的java,了解java首先要了解下计算机语言的发展历史 机器语言--->汇编语言--->--->高级语言(面向过程的语言和面向对象的语言) 机器语言 每一个计算机 ...
- Pad控件 UIPopoverController的介绍与使用(Pad的专属菜单控件、Swift版本)
UIPopoverController 是iPad特有控件,iOS9之前,在iOS上也可以使用,在iOS9之后,只能用于Pad上. 如果非要在iOS上使用,编译不会有问题,运行后会崩溃,报错如下: T ...
- a里面不能嵌套a
1. <a href=""> <a href=""></a></a> 会被浏览器解析为 2. <a hre ...
- 关于JavaScript中连等赋值那点事
今天看了前端网上关于JS的题目,其中有一道题目挺有意思的.如下 var a = b =10; (function(){ var a = b = 20; })(); console.log(a); co ...
- [SinGuLaRiTy] COCI 2011~2012 #2
[SinGuLaRiTy-1008] Copyright (c) SinGuLaRiTy 2017. All Rights Reserved. 测试题目 对于所有的题目:Time Limit:1s ...
- JavaScript原生Array常用方法
JavaScript原生Array常用方法 在入门Vue时, 列表渲染一节中提到数组的变异方法, 其中包括push(), pop(), shift(), unshift(), splice(), so ...
- canvas画布
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- android开发之-Android 开发之4.0界面设计原则-整理
设计原则: 一.让人着迷: 1.给人惊喜:使用漂亮的界面.精心的动画.适时的音乐. 2.真实的对象比按钮和菜单更有趣 这句话的意思是:使用描述描述性的图标作为快捷方式,界面美观 当然这个快捷方 ...