设为首页 收藏本站
查看: 594|回复: 0

[经验分享] python快速入门一

[复制链接]

尚未签到

发表于 2017-4-27 08:01:30 | 显示全部楼层 |阅读模式
1)字符串:
字符串有其特有的索引规则:第一个字符的索引是 0,最后一个字符的索引是 -1
>>> prstr = 'Python'
>>> pystr[0]
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
pystr[0]
NameError: name 'pystr' is not defined
>>> pystr[0]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
pystr[0]
NameError: name 'pystr' is not defined
>>> pystr = "abcde"
>>> pystr[0]
'a'
>>> pystr='Python'
>>> pystr[0]
'P'
>>> pystr[2:5]
'tho'
>>> pystr[:2]
'Py'
>>> pystr[2:]
'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= [1, 2, 3, 4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[:3]
[1, 2, 3]
>>> aList[1]
2
>>> atuple = ('robots', 77, 92, 'try')
>>> atuple
('robots', 77, 92, 'try')
>>> atuple[3]
'try'
>>> atuple[:3]
('robots', 77, 92)
>>> atuple[1] = 55
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
atuple[1] = 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[key]
SyntaxError: invalid syntax
>>> for key in adict :
print(key , adict[key])

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 = [x ** 2 for x in range(4)]
>>> for i in squared:
print(i)

0
1
4
9
>>> sqdEvens = [x ** 2 for x in range(8) if not x % 2]
>>> 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 (Dec  4 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 is  john doe
>>> foo2 = FooClass('test')
-----  test
>>> foo2.showname()
your name is  test
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) [MSC v.1500 32 bit (Intel)]'

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[0]
1
>>> a[0]=1
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a[0]=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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-369689-1-1.html 上篇帖子: python字符串处理函数 下篇帖子: python 获取脚本所在目录
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表