码迷,mamicode.com
首页 > 编程语言 > 详细

python学习过程之从零开始

时间:2016-06-15 12:53:08      阅读:333      评论:0      收藏:0      [点我收藏+]

标签:python学习宝典

用于交互使用:

>>> user = raw_input(‘Enter login name:‘)

Enter login name:root

>>> print user

root

交互使用,将输出的数字型转化为整形,并通过% 进行替换

注解:%s 表示由一个字符串替换,%d表示由一个整数来替换%f由一个浮点数来替换

>>> num = raw_input(‘Now enter a number:‘)

Now enter a number:1024

>>> print ‘Doubling your number: %d‘ % (int(num) * 2)

Doubling your number: 2048

>>>

可以通过调用内建函数help查看对应生词函数的使用帮助

help(raw_input)  

井号后都是注释部分

######ffffffffffffffff

运算符 

+ - * / // % **

//:(用于浮点除法,对结果进行四舍五入)

变量和赋值操作。

>>> counter=0    ####整数

>>> miles = 1000.0   #####浮点数

>>> name = ‘Bob‘  #####字符串

>>> counter = counter +1  ####对1个整数加1

>>> kilometers = 1.609 * miles   ####浮点数乘法赋值

>>> print "%f miles is the same as %s km" % (miles,kilometers)

1000.000000 miles is the same as 1609.0 km

>>>

数字类型:

int(有符号整数)

long(长整数)

bool(布尔值)

float(浮点值)

complex(负数)

[:] 可以截取到字符串内容

>>>pystr = ‘Python‘

>>> pystr

‘Python‘

>>> pystr[2:5]

‘tho‘

>>> 

[:2] 字符串从0开始截取到第二个字符串(不包含第二个字符串,s)

>>> iscool = ‘is cool!‘

>>> iscool[:2]

‘is‘

>>>

 [3:] 字符串从3开始截取到最后(不包含第:三个字符串,s)

>>> iscool[3:]

‘cool!‘

>>>

[-1] 截取最后一个字符串

>>> iscool[-1]

‘!‘

>>>  

可以加空格

>>> pystr + ‘ ‘ +iscool

‘Python is cool!‘

>>>

字符串*2

>>> pystr * 2

‘PythonPython‘

>>>  

将特殊字符*20

>>> ‘-‘ * 20

‘--------------------‘

>>>

添加回车符

>>> pystr = ‘‘‘python

... is cool‘‘‘

>>> pystr

‘python\nis cool‘

>>> print pystr

python

is cool

>>>  

列表与切片

>>> aList = [1,2,3,4]

>>> aList

[1, 2, 3, 4]

>>> aList[0]

1

>>> aList[2:]

[3, 4]

>>> aList[1] = 5  ####将分片1替换成 5

[1, 5, 3, 4]

>>> aTuple = (‘robots‘, 77, 93, ‘try‘)

>>> aTuple

(‘robots‘, 77, 93, ‘try‘)

>>> aTuple[:3]

(‘robots‘, 77, 93)

>>>

 字典,由键值对构成,字典元素用大括号包裹

>>> aDict = {‘host‘:‘earth‘}

>>> aDict[‘port‘] = 80

>>> aDict

{‘host‘: ‘earth‘, ‘port‘: 80}

>>>

>>> aDict.keys()  #####将字典的键值对取出

[‘host‘, ‘port‘]

>>>  

>>> aDict[‘host‘] ###可以取出字典对应的键值对。

‘earth‘

>>> aDict

{‘host‘: ‘earth‘, ‘port‘: 80}  ###可以取出字典对应的键值对。

>>> aDict[‘port‘]

80

>>>

while小程序

>>> counter = 0

>>> while counter < 3:

...     print ‘loop #%d‘ % (counter)

...     counter += 1

...

loop #0

loop #1

loop #2

for小程序,Python中的for接受可迭代对象作为其参数,每次迭代其中一个

(如下代码所示:print默认给每一行添加了换行符)

>>> print ‘I like to use the Internet for:‘

I like to use the Internet for:

>>> for item in [‘e-mail‘, ‘net-surfing‘, ‘homework‘, ‘chat‘]:

...     print item

...

e-mail

net-surfing

homework

chat

>>>

小例子

>>> for eachNum in range(3):

...     print eachNum

...

0

1

2

>>>

range()函数和len()函数一起使用,显示每一个元素及其索引值

 >>> for i in range(len(foo)):

...     print foo[i], ‘(%d)‘ % i

...

a (0)

b (1)

c (2)

>>>

循环一般有个约束,要么循环索引,要么循环元素,enumerate同时做到了这2点

>>> for i, ch in enumerate(foo):

...     print ch, ‘(%d)‘ % i

...

a (0)

b (1)

c (2)

>>>  

列表解析:用for循环将所有值放到列表中,例如range(4)会得到0,1,2,3循环时

>>> squared = [x ** 2 for x in range(4)]

>>> for i in squared:

...     print i

...

0

1

4

9

列表解析,较复杂的操作,将符合的值挑选出放进列表:例如  if not x % 2将余数不能整除2的剔除,剩余的数在 x ** 2

>>> sqdEvens = [x ** 2 for x in range(8) if not x % 2 ]

>>> for i in sqdEvens:

...     print i

...

0

4

16

36

>>>


#!/usr/bin/env python

filename = raw_input(‘Enter file name: ‘)

fobj = open(filename, ‘r‘)   选择需要打开的文件名,r表示读取,w表示写入,a表示添加

for i in fobj:

        print i,   这里加,逗号的作用是为了抑制文本里的换行符,因为文本里已自带换行符

fobj.close() 

给代码添加错误检测机异常处理功能,将他们封装在try-except中

#!/usr/bin/env python

try:

        filename = raw_input(‘Enter file name:‘)

        fobj = open(filename, ‘r‘)

        for i in fobj:

                print i,

        fobj.close()

except IOError, e:   

        print "eeeee", e

执行脚本后的错误异常,说明没有找到a.t文本

[root@iZ28c21psoeZ zby]# ./open_bak.py

Enter file name:a.t

eeeee [Errno 2] No such file or directory: ‘a.t‘  

python 中的函数使用小括号()调用的,函数在调用前必须先定义,如果函数中没有return语句,就会自动返回None对象。

如下是如何定义的小例子

>>> def function_name(arguments):

...     "optional documentation string"

...     function_suite

...

>>> 

接下来如何做,请耐心观看,如何调用函数,

这个函数,做的是在我的值上加上我的活,他接受一个对象,并将它的值加到自身,然后返回和。

python调用函数与其他高级语言一样,函数名加上函数运算符,一对小括号。

>>> def addMe2Me(x):

...     ‘apply + operation to argument‘

...     return (x + x)

...

>>> addMe2Me(4.25)

8.5

>>> addMe2Me(10)

20

>>> addMe2Me(102)

204

>>> addMe2Me(python)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name ‘python‘ is not defined

>>> addMe2Me(‘python‘)

‘pythonpython‘

>>>

模块可以包含可执行代码,函数和类或者这些东西的组合,

一个模块创建后,可以从另一个模块中使用import语句导入这个模块来使用。

接着向下看,如何导入模块

>>> import sys

>>> sys.stdout.write(‘Hello, World!\n‘)

Hello, World!

>>> sys.platform

‘linux2‘

>>> sys.version

‘2.6.6 (r266:84292, Jan 22 2014, 09:42:36) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)]‘

练习题:

使用while语句和for语句,输出一个0到10 的数,确保是0到10 而不是0到9 或者1到10

>>> i = 0

>>> while i < 11:

...     print i   这边一定要先打印,在逐步加1

...     i += 1

...

0

1

2

3

4

5

6

7

8

9

10

>>>

for循环

>>> for n in range(11):

...     print n

...

0

1

2

3

4

5

6

7

8

9

10 

 

条件判断,判断1个数是整数还是负数,或者等于0 ,开始先用固定的数值,然后修改代码支持,用户输入数值进行判断。

>>> n = int(raw_input(‘nihao‘))

nihao123

>>> if n < 0:

...     print ‘negative‘

... elif n > 0:

...     print ‘positive‘

... else:

...     print ‘zero‘

...

positive

>>>


python学习过程之从零开始

标签:python学习宝典

原文地址:http://bjzby.blog.51cto.com/4084070/1789426

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!