123sw 发表于 2017-4-27 08:01:30

python快速入门一

1)字符串:
字符串有其特有的索引规则:第一个字符的索引是 0,最后一个字符的索引是 -1
>>> prstr = 'Python'
>>> pystr
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
pystr
NameError: name 'pystr' is not defined
>>> pystr
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
pystr
NameError: name 'pystr' is not defined
>>> pystr = "abcde"
>>> pystr
'a'
>>> pystr='Python'
>>> pystr
'P'
>>> pystr
'tho'
>>> pystr[:2]
'Py'
>>> pystr
'thon'
>>> pystr[-1]
'n'
>>> pystr * 2
'PythonPython'
>>> '-' * 2
'--'
>>> pystr[-1:15]
'n'
>>> pystr[-1:15]
'n'
>>> pystr[-1:-3]
''
>>> pystr[-6:-1]
'Pytho'
>>> pystr[-6:]
'Python'
>>> pystr[-6:0]
''
>>> pystr[-6:-2]
'Pyth'
2)列表和元组
列表和元组有几处重要区别,列表元素用中括号([])包裹,元素的个数及元素的值可以改变,元组元素用小括号(())包裹,不可以更改,尽管它们的内容可以改变,元组可以看成是只读的列表。通过切片运算([] 和[:])可以得到子集。
>>> aList=
>>> aList

>>> aList
1
>>> aList

>>> aList[:3]

>>> aList
2
>>> atuple = ('robots', 77, 92, 'try')
>>> atuple
('robots', 77, 92, 'try')
>>> atuple
'try'
>>> atuple[:3]
('robots', 77, 92)
>>> atuple = 55
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
atuple = 55
TypeError: 'tuple' object does not support item assignment
3)字典
字典是Python中的映射数据类型,工作原理类似Perl中的关联数组或者哈希表,有键-值(key-value)组成,几乎所有类型的Python对象都可以用作键。值可以是任意类型的python对象,字典元素用大括号({})包裹。
>>> adict = {'host' : 'earth'}
>>> adict['port'] = 80
>>> adict
{'host': 'earth', 'port': 80}
>>> adict.keys()
dict_keys(['host', 'port'])
>>> dir(adict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> adict.values
<built-in method values of dict object at 0x014C7270>
>>> adict.values()
dict_values(['earth', 80])
>>> adict.pop()
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
adict.pop()
TypeError: pop expected at least 1 arguments, got 0
>>> adict['host']
'earth'
>>> for key in adict:
print key , adict
SyntaxError: invalid syntax
>>> for key in adict :
print(key , adict)

host earth
port 80
4)if …elif…else
1.print在3.0版本后改变为print()
2.raw_input在3.0版本后改变为input()
3.python一直让我不解的一个问题,代码块,现在看来没有什么好担心的了,因为它的缩进做到很好。约定有点时候带来的效率更高。不得不喜欢python简洁的语法。
>>> if 3<0:
print ' ok !'
SyntaxError: invalid syntax
>>> if 3 < 0
SyntaxError: invalid syntax
>>> if 3<0:
print('ok----0')
print('ok----1')
elif 3>0:
SyntaxError: invalid syntax
>>> if 3<0:
print('ok----0')
print('ok----1')
elif 3>0:
SyntaxError: unindent does not match any outer indentation level
>>> if 3<0:
print('ok----0')
print('ok----1')

>>> if 3>0:
print('ok----0')
print('ok----1')

ok----0
ok----1
>>> if 3<0:
print('ok----0')
print('ok----1')
else print(111)
SyntaxError: invalid syntax
>>> if 3<0:
print('ok----0')
print('ok----1')
else print(111)
SyntaxError: invalid syntax
>>> a = input("a:")
b = input("b:")
if(a > b):
print a, " > ", b
else:
print a, " < ", b
a:1
>>> a = input("a:")
b = input("b:")
if(a > b):
print a, " > ", b
else:
print a, " < ", b
a:333
>>> a = input("a:")
a:1
>>> b = input("b:")
b:3
>>> if(a > b):
print a, " > ", b
else:
print a, " < ", b
SyntaxError: invalid syntax
>>> if(a > b):
print (a, " > ", b)
else:
print (a, " < ", b)
SyntaxError: expected an indented block
>>> if(a > b):
print (a, " > ", b)
else:
print (a, " < ", b)

1<3
>>> if(a < b):
print(a, " < " b)
SyntaxError: invalid syntax
>>> if(a < b )
SyntaxError: invalid syntax
>>> if(a < b ):
print(a, " < ", b)
else:
print(a, "> ", b)

1<3
5)While
While和if没什么区别,只是需要注意:要使用缩进来分隔每个子代码块
>>> counter = 0
>>> while counter < 3:
print('loop #%d' % (counter))
counter += 1

loop #0
loop #1
loop #2
6)For
>>> import sys
>>> for num in ['1','2','3','4']:
sys.stdout.write(num)
1234
>>> foo = 'abc'
>>> for i in range(len(foo)):
print(foo, '%d' % i)

a 0
b 1
c 2
>>> for i , ch in enumerate(foo):
print( ch, '%d' % i)

a 0
b 1
c 2
7)列表解析
>>> squared =
>>> for i in squared:
print(i)

0
1
4
9
>>> sqdEvens =
>>> for i in sqdEvens
SyntaxError: invalid syntax
>>> for i in sqdEvens:
print i
SyntaxError: invalid syntax
>>> for i in sqdEvens:
print(i)

0
4
16
36
8)文件
>>> fobj = open('C:\GHOSTERR.TXT','r')
>>> for eachLine in fobj:
print(eachLine)

*********************************
Date   : Tue Oct 21 16:26:47 2008
Error Number: (440)
Message: Ghost cannot run on Windows based systems.
Please boot your system into Dos and then run Ghost or
alternatively, run Ghost32 (Ghost for Windows).
Version: 11.0.0.1502 (Dec4 2006, Build=1502)
OS Version: DOS v5.50
Command line arguments:
Active Switches :
AutoName
PathName            :
DumpFile            :
DumpPos             : 0
FlagImplode         : 0
FlagExplode         : 0

Operation Details :
Total size.........0
MB copied..........0
MB remaining.......0
Percent complete...0%
Speed..............0 MB/min
Time elapsed.......0:00   
Time remaining.....0:00   

Program Call Stack
AbortLog
Generic_Abort
main

Call Stack
0x0039623c
0x0009cbd1
0x0009c40c
0x0009bae7
0x0009d6ee
0x00003cad
0x0039f468
End Call Stack


Start heap available: 0
Cur   heap available: 15728640
Total Memory:         1064480768

Allocated
1024 DpmiDjgpp.cpp:56
Free

Fat details:

NTFS details:
----------------

NTFS Global Flags:
----------------
contiguousWrite=0 forceDiskClusterMapping=0
inhibitCHKDSK=0 ignoreBadLog=0 ignoreCHKDSKBit=0
enable_cache=0 xfrbuflen=0
last_attr_type = 0
loadExact = 0
----------------
>>> fobj.close()
9)类
self , 它是类实例自身的引用
当一个实例被创建,__init__()就会被自动调用。不管这个__int__()是自定义的还是默认的。
>>> class FooClass(object):
"""my very first class : FooClass"""
version = 0.1
def __init__(self, nm='john doe'):
"""constructor"""
self.name = nm
print('----- ' ,nm)
def showname(self):
"""display instance attribute and class name"""
print('your name is ', self.name)

>>> fool = FooClass()
-----john doe
>>> fool.show
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
fool.show
AttributeError: 'FooClass' object has no attribute 'show'
>>> fool.showname()
your name isjohn doe
>>> foo2 = FooClass('test')
-----test
>>> foo2.showname()
your name istest
10)模块
当你创建了一个 Python 源文件,模块的名字就是不带 .py 后缀的文件名。一个模块创建之后, 你可以从另一个模块中使用 import 语句导入这个模块来使用。
>>> import sys
>>> sys.stdout
<idlelib.rpc.RPCProxy object at 0x013F59D0>
>>> sys.stdout.write('hello world')
hello world
>>> sys.platform
'win32'
>>> sys.version
'3.1.2 (r312:79149, Mar 21 2010, 00:41:52) '

1)“多元”赋值
>>> x,y,z = 1,2,'a.string'
>>> x
1
>>> y
2
>>> z
'a.string'
>>> x = 2
>>> x
2
>>> (x,y,z)=(1,2,3)
>>> x
1
>>> y
2
>>> z
3
>>> x=1
>>> x=3
>>> (x,y,z)
(3, 2, 3)
>>> a=(1,2,3)
>>> a
1
>>> a=1
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a=1
TypeError: 'tuple' object does not support item assignment
>>>
无需中间变量,就可以交换值
>>> x,y = 1,2
>>> x,y = y, x
>>> x
2
>>> y
1
>>> x,y
(2, 1)
>>>
页: [1]
查看完整版本: python快速入门一