用import导入模块,然后按照“模块.函数”的格式使用这个模块的函数,如
>>> import math
>>> math.floor(23.96)
23.0
在使用了“form模块import函数”这种形式的import命令之后,就可以直接使用函数,而不需要模块名作为前缀了,如
>>> from math import sqrt
>>> sqrt(9)
3.0
CMath模块可以实现处理复数,如
>>> cmath.sqrt(-9)
3j
程序
在IDLE中,file->new file会弹出一个编辑窗口,在里面编辑如下
name = raw_input("what is your name")
print 'hello,' + name + '!'
然后file-save 保存为hell.py,然后F5运行,则在解释器中出现结果,如
>>> ================================ RESTART ================================
>>>
what is your name55
hello,55!
或者双击hell.py,则命令行窗口一闪而逝。
print 'hello ' + raw_input('your name:')
print 'hello ' + input('your name:')
结果如下
your name:55
hello 55
your name:55
Traceback (most recent call last):
File "E:/work/Code/python/hell.py", line 2, in <module>
print 'hello ' + input('your name:')
TypeError: cannot concatenate 'str' and 'int' objects
如果要书写一个跨多行的长字符串,可以使用三个引号代替普通引号,如
print '''This is a long string.
it continues here.
and it's not over yet.
"hello world!".
still here.'''
结果如下
This is a long string.
it continues here.
and it's not over yet.
"hello world!".
普通字符串也可以跨行,如果一行之中最后一个字符是反斜线,那么,换行本身就“转义”了,也就是被忽略了(同时适用于表达式),如
print 'This is a long string.\
it stop here.'
结果
This is a long string.it stop here.
原始字符串不会吧反斜线当做特殊字符,在元是字符串中输入的每个字符都会与书写的方式保持一致,如