Python体验(01)
时间:2010-11-20 来源:许明会
下面通过一系列简单示例来体验,代码可以直接粘贴保存,都通过测试。
案例1:
#用于注释,但第一行#!也给程序指出本代码是靠/usr/bin/python执行的,所以文件名可以不是py
如果你乐意,你可以给helloworld.py 增加属性X,这样你可以把它改成任意的文件名直接执行,如hello。
#filename:helloworld.py
print '\n\tHello World! That\'s Python!\n'
#if you want the .py file to be executable:chmod a+x helloworld.py
案例2:
变量不用声明可以直接赋值;if/elif/else语句不用包括判断语句且以:结尾;
#filename:raw_input.py
number = 23 #here no ; but you can add ; either
guess = int(raw_input("Enter an Integer:")); #string,can use ' or "
if guess == number: #notice: no () and there's a :
print 'Congratulations, you guessed it.'
print '(but you do not win any prizes!)'
elif guess < number:
print "No, It's a little higher than what you input."
else:
print 'No,It\'s a little lower than what you input.'
print "Done!";
案例3:猜数字游戏,5次猜不对就退出
while循环,break跳出;省去了类似C语言的{}而改用对齐来决定语句块
#filename:while.py
number = 23
Hitting = False
loop = 5
while not Hitting:
guess = int(raw_input("Guess what(" + str(loop) +" times left):"))
loop = loop -1 ;
if loop == 0:
print "\tToo stupid, you lost!"
break;
if guess > number :
print "\tYour number is bigger than that."
elif guess < number:
print "\tYour number is littler than that."
else:
Hitting = True;
print "\tYou WIN, Excellent Baby!"
print "\t--===--[DONE]--===--"
#the Done statement is line to while, so running out of while then "Done" execute.
示例4:函数,默认参数,有返回值;DocString
代码 #!/usr/bin/python#filename:function.py
def value(num = 3): #there's default parameter.
'''Coded by Phoenix :
RET(X) = X^X''' #DocStrings
ret = 1;
for i in range(0,num): #notice, there is :
ret = ret * num
return ret
number = int(raw_input("Input a number:"))
print value()
print number**number
print value(number) #output the x^x, by the way, you can use: x**x
print value.__doc__ #output DocStrings
相关阅读 更多 +