Python基础教程(自学记录)

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Python基础教程(自学记录)

第一章快速改造:基础知识

1.2交互式解释器

在IDLE编辑器,在提示符后输入help然后按回车;也可以按下F1获得有关IDLE的帮助信息

1.4数字和表达式

1/2返回0,整除除法;1.0/2返回0.5,用一个或者多个包含小数点的数字参与计算。另外改变除法的执行方式:from_future_import division

//可以实现整除,1.0//2.0返回0.0

%取余数;**幂运算;

>>> 1/2

>>> 1.0/2

0.5

>>> 1.0//2.0

0.0

>>> 10%3

1

>>> 9**(1/2)

1

>>> 9**(1.0/2)

3.0

>>> 2.75%0.5

0.25

>>> -9%4

3

>>> -3%2

1

>>> -3/2

-2

1.4.1长整数

普通整数不能大于2147483647也不能小于-2147483648,若更大的数,可以使用长整数。长整数结尾有个L,理论上小写也可以,不过为了便于识别,尽可能用大写。

1.4.2十六进制和八进制

0XAF返回175 ,十六进制;

010返回8,八进制

>>> 0xAF

175

>>> 010

8

1.5变量

包含字母、数字和下划线。首字母不能是数字开头。

1.8函数

Pow计算乘方:pow(2,3),2**3均返回8;pow等标准函数称为内建函数。

Abs(-10)求绝对值,返回10;round(1.0/2.0)返回1.0,把浮点数四舍五入为最接近的整数值。

>>> pow(2,3)

8

>>> 2**3

8

>>> abs(-10)

10

>>> round(1.0/2.0)

1.0

Traceback (most recent call last):

File "", line 1, in

'Hello, '+5

TypeError: cannot concatenate 'str' and 'int' objects

>>>

需要保证两边是一样的字符串,而有其他格式要报错的

1.11.3字符串表示str和repr- 两个均为函数,事实上str是一种类型

Str会将值转换为合理形式的字符串。另外一种是通过repr函数,创建一个字符串。

Repr(x)也可以写作`x`实现(注意:`是反引号),python3.0中已经不适用反引号了

>>> print 'hello,world'

hello,world

>>> print repr('hello,world')

'hello,world'

>>> print str('hello,world')

hello,world

>>> print 1000L

1000

>>> 1000L

1000L

>>> print repr(1000L)

1000L

>>> print str(1000L)

1000

>>> tmp=42

>>> print 'The number is:'+tmp

Traceback (most recent call last):

File "", line 1, in

print 'The number is:'+tmp

TypeError: cannot concatenate 'str' and 'int' objects >>> print 'The number is:'+`tmp`

The number is:42

>>> print 'The number is:'+str(tmp)

The number is:42

>>> print 'The number is:'+repr(tmp)

The number is:42

1.11.4 input和raw_input的比较

>>> name=input("What's your name:") What's your name:Gumby

Traceback (most recent call last):

File "", line 1, in

name=input("What's your name:") File "", line 1, in NameError: name 'Gumby' is not defined >>> name=input("What's your name:") What's your name:'Gumby'

后面输入的字符串增加了引号不报错。>>> input('Enter a number:')

Enter a number:3

3

>>> name=input("What's your name:") What's your name:'Gumby'

>>> raw_input("What's your name:") What's your name:Gumby

'Gumby'

>>> raw_input("What's your name:")

相关文档
最新文档