学习Python也有个把月了,最近整理自己初学的代码示例,一个是为了增加自己对细节的把握,一个是让像我一样的初学者能够熟练地使用基础,基础的重要性就不说了,我希望自己能够把这些精巧的小而短的示例分享给大家,共同进步

#help(execfile)
Help on built-in function execfile in module __builtin__:
execfile(...)
execfile(filename[, globals[, locals]])
Read and execute a Python script from a file.
The globals and locals are dictionaries, defaulting to the current
globals and locals. If only globals is given, locals defaults to it.
# 类对象命名规则
class MyClass: # Python中的类名采用CapWords约定,单词首字母大写,其他小写
__username=‘ ‘ # 类的私有属性、私有方法要有两个下划线前缀
def __init__(self,username):
self.__username=username
def getUserName(self): #共有方法名首字母小写,其后每个单词首字母大写
return self.__username
if __name__==‘__main__‘:
myclass=MyClass(‘admin‘)
print myclass.getUserName()
# 注释
# 单行注释
# 行内注释:可以#+空格 来区分好看
# 注释块:在块中用单行只有一个#来分割注释
#
# 中文注释:cp936
# 跨平台注释:除了win以外平台
# 加!# /usr/bin/python
# 十进制也有浮点型
>>> from decimal import Decimal
>>> dec=Decimal(‘1.1‘)
>>> dec# 查看变量dec类型
Decimal(‘1.1‘)
>>> dec+2.6#十进制浮点型与浮点型不能直接相加,属于一个单独的类型,是准确的没有损失
Traceback (most recent call last):
File "", line 1, in 
dec+2.6
TypeError: unsupported operand type(s) for +: ‘Decimal‘ and ‘float‘
>>> dec+Decimal(‘2.6‘)
Decimal(‘3.7‘)
#write Fibonacci series up to n
def fibonacci(n):
"""Print a Fibonacci series up to n"""
a,b=0,1
while a
print a
a,b=b,a+b
#转义字符
>>> print ‘what\‘s your name‘
what‘s your name
#repr()的应用
#Python 有办法将任意值转为字符串:将它传入repr()或str()函数。
#函数str()用于将值转化为适于人阅读的形式,而repr()转化为供解释器读取的形式
#某对象没有适于人阅读的解释形式的话,str()会返回与repr()等同的值。
# The repr() of a string adds string quotes and backslashes:
>>> hello=‘hello world\n‘‘
>>> print hello
hello world
>>> hellos=repr(hello)#保持了原有状态
>>> print hellos
‘hello world\n‘
#实现用户登录
# -*- coding: cp936 -*-
username=raw_input(‘您的姓名:‘)
password=raw_input(‘您的密码:‘)
if (username==‘admin‘)and(password==‘admin‘):
print ‘恭喜你!您输入的用户名和密码合法,登录成功!‘
#运用for将字符串当做字符串list迭代
# -*- coding: cp936 -*-
string=‘this is a good day‘
for i in string:
print i
#iter()内置函数可以返回迭代器(iterator)
# -*- coding: cp936 -*-
#所有迭代工具的内部工作都是在循环调用next方法,并且捕捉StopIteration异常来确定何时离开
#iter()内置函数可以返回迭代器(iterator)
a=[‘a‘,‘b‘,‘c‘,‘d‘]
my=iter(a) # 返回iterator
print my.next() # 使用迭代工具将my输出
print my.next()
print my.next()
print my.next()
#或者使用
#for i in tier(a):
# Print i
>>> help(iter)
Help on built-in function iter in module __builtin__:
iter(...)
iter(collection) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.

在后台,for语句在容器对象中调用iter()。 该函数返回一个定义了next()方法的迭代器对象,它在容器中逐一访问元素。没有后续的元素时,next()抛出一个StopIteration异常通知for语句循环结束。

#两个不同的join的区别
>>>fromstringimportjoin
>>>help(join)
Helpon function joininmodule string:
join(words, sep=‘ ‘)
join(list[,sep])-> string
Return a string composed of the wordsinlist, with
intervening occurrences of sep. The default separatorisa
single space.
(joinfieldsandjoin are synonymous)
>>> join=str.join
>>>help(join)
Helpon method_descriptor:
join(...)
S.join(sequence)-> string
Return a string whichisthe concatenation of the stringsinthe
sequence. The separator between elementsisS.
#print 中的+和,区别;zip(压缩)list为元祖列表
>>> names=[‘j‘,‘f‘,‘w‘,‘min‘,‘yi‘]
>>> ages=[12,13,15,52,66]
>>> for name,age in zip(names,ages):
print name,‘ is ‘,age#print 中+号只能连接string;可以使用,来分隔;若使用+,则需要str(age)
j is 12
f is 13
w is 15
min is 52
yi is 66
#enumerate()返回index和value对
#enumerate()返回一个迭代器
lis=[‘this‘,‘is‘,‘a‘,‘good‘,‘day‘]
for index,value in enumerate(lis):
print index,‘ ‘,value
#类似的do while循环改进
user=raw_input(‘输入你的用户名:‘)
while user: #user 只要非空,持续输出
print ‘确认:您输入的用户名是‘+user
user=raw_input(‘输入你的用户名:‘)
#改进版本,不要重复代码,采用判断if和break来跳出循环
while True:
user2=raw_input(‘输入你的用户名:‘)
if not user2: #判断是:not空,则执行break
break
print ‘确认:您输入的用户名是‘+user

更新时间 :2014年6月8日19:40:13

http://fergusj.blog.51cto.com/8835051/1423711