您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python简明入门教程

2025/10/3 6:34:15发布18次查看
本文实例讲述了python简明入门教程。分享给大家供大家参考。具体如下:
一、基本概念
1、数
在python中有4种类型的数——整数、长整数、浮点数和复数。
(1)2是一个整数的例子。
(2)长整数不过是大一些的整数。
(2)3.23和52.3e-4是浮点数的例子。e标记表示10的幂。在这里,52.3e-4表示52.3 * 10-4。
(4)(-5+4j)和(2.3-4.6j)是复数的例子。
2、字符串
(1)使用单引号(')
(2)使用双引号()
(3)使用三引号('''或)
利用三引号,你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双引号。例如:
'''this is a multi-line string. this is the first line.this is the second line.what's your name?, i asked.he said bond, james bond.'''
(4)转义符
(5)自然字符串
自然字符串通过给字符串加上前缀r或r来指定。例如rnewlines are indicated by \n。
3、逻辑行与物理行
一个物理行中使用多于一个逻辑行,需要使用分号(;)来特别地标明这种用法。一个物理行只有一个逻辑行可不用分号
二、控制流
1、if
块中不用大括号,条件后用分号,对应elif和else
if guess == number: print 'congratulations, you guessed it.' # new block starts hereelif guess ')except eoferror: print '\nwhy did you do an eof on me?' sys.exit() # exit the programexcept: print '\nsome error/exception occurred.' # here, we are not exiting the programprint 'done'
2、引发异常
使用raise语句引发异常。你还得指明错误/异常的名称和伴随异常 触发的 异常对象。你可以引发的错误或异常应该分别是一个error或exception类的直接或间接导出类。
class shortinputexception(exception): '''a user-defined exception class.''' def __init__(self, length, atleast): exception.__init__(self) self.length = length self.atleast = atleastraise shortinputexception(len(s), 3)
3、try..finnally
import timetry: f = file('poem.txt') while true: # our usual file-reading idiom line = f.readline() if len(line) == 0: break time.sleep(2) print line,finally: f.close() print 'cleaning up...closed the file'
九、python标准库
1、sys库
sys模块包含系统对应的功能。sys.argv列表,它包含命令行参数。
2、os库
os.name字符串指示你正在使用的平台。比如对于windows,它是'nt',而对于linux/unix用户,它是'posix'。
os.getcwd()函数得到当前工作目录,即当前python脚本工作的目录路径。
os.getenv()和os.putenv()函数分别用来读取和设置环境变量。
os.listdir()返回指定目录下的所有文件和目录名。
os.remove()函数用来删除一个文件。
os.system()函数用来运行shell命令。
os.linesep字符串给出当前平台使用的行终止符。例如,windows使用'\r\n',linux使用'\n'而mac使用'\r'。
os.path.split()函数返回一个路径的目录名和文件名。
>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.existe()函数用来检验给出的路径是否真地存在。
希望本文所述对大家的python程序设计有所帮助。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product