Python基础教程

来源:互联网 发布:超级优化有几个女主角 编辑:程序博客网 时间:2024/05/16 14:45

本教程不包括Python的安装,IDE采用Spyder(Pytho2.7)

1.

>>> print pow(2,3);8>>> print 2**3;8

这里pow函数表示乘方,与**功能相同。

    2.
>>> abs(-10)10

abs函数用来求一个数的绝对值。

    3.
>>> round(0.6)1.0>>> round(0.4)0.0

round函数将浮点数四舍五入为最接近的整数值。

    4.
>>> import math>>> math.floor(32.9)32.0>>> int(math.ceil(32.9))33

这里floor函数用来得到小于此数的最大整数, ceil 函数用来得到大于此数的最小整数值。

    5.
>>> foo=math.sqrt>>> foo(4)2.0

可以将函数的功能引用给一个新的符号,此符号的使用可代替原函数。

    6.
>>> import cmath>>> cmath.sqrt(-1)1j

cmath是(Complex math)的缩写,即为Python中对复数的处理包,将其导入,便可以处理复数。

    7.
>>> "\"Hello, world!\" she said"'"Hello, world!" she said'

转义字符的使用。

    8.
>>> print repr("hello")'hello'>>> print repr(1000)1000>>> temp=42>>> print "我是你"+str(temp)我是你42>>> print "我是你"+repr(temp)我是你42>>> stt="hello">>> print "我是你"+str(stt)我是你hello>>> print "我是你"+repr(stt)我是你'hello'

官方说法:通过str函数,它会把值转换为合理形式的字符串,以便用户可以理解;另一种是通过repr函数,它会创建一个字符串,以合法的Python表达式的形式来表示值。
具体理解看以上例子。

    9.
>>> input("Enter a number:")Enter a number:33>>> raw_input("Enter a number:")Enter a number:3'3'

input函数会默认你输入的是合法的Python表达式,比如你想要输入一个字符串,那么就要输入“Hello, world!”,即带着引号输入。然而raw_input则将输入当作原始数据,然后将其放入字符串中。