Python快速入门

for version 3.1

以下所以程序已经过测试 。转载请注明出处。

# 注释
# This is a annotation

 # 变量和赋值

= "Hello World"

 # print格式化输出

print(v)
print("The length of (%s) is %d" %(v, len(v)))
print("dec: %d, oct: %o, hex: %x, float: %5f" %(64,64,64,64))

 # 使用str函数将对象转化为字符串

sum = 2000
print(str(sum) + " dollas")

 # 使用int函数将对象转化为数字

fund = "500"
print(int(fund) + 1500)

 # 列表(list)

ls = ['C#''VB''C++''Java''Python''Ruby']
print(ls)
print(ls[0])

 # 字典(dictionary)

dic = {1:'John'2:'Jane'3:'Jack'4:'James'5:'Julie'}
print(dic)
print(dic[1])

 # 简单的循环

for i in range(0,5): print(i)
for v in ls: print(v)
for k in dic: print("%s: %s" %(str(k), dic[k]))

 # range函数

r1 = range(1,10)        # 从1到10(不包括10),步长为1
for i in r1: print(i)

r2 
= range(-1,-20,-2)    # 从-1到-20(不包括-20),步长为-2
for j in r2: print(j)

 # 条件判断

= int(input("enter an integer: "))
if x==0:
    
print("zero")
elif x<0: 
    
print("negative")
else:
    
print("positive")

 # 定义函数

def sum(a, b): return a + b;
def inc(a, b=0): return a + b;
print(sum(199))    # return 100
print(inc(199))      # return 100
print(inc(100))        # return 100

 # 异常处理

= input("Type something: ")
if s=="":
    
raise Exception("You must input something...")

try:
    
print(int(s))
except Exception as err:
    
print(err)
finally:
    
print("Bye Bye!")

 # 简单的文件处理

代码
data = [11235813213455]
path 
= "abc.txt"

fw 
= open(path, "w")    # 使用写方式打开,文件不存在则创建
fw.write("The Fibonacci:\n")
for i in range(0, len(data)):
    
if i < len(data) - 1: fw.write("%d, " %(data[i]))
    
else: fw.write("%d..." %(data[i]))        
fw.close()    
# 表忘记关闭文件

fo 
= open(path, "r")    # 使用读方式打开文件
for line in fo: print(line)    
fo.close()    
# 表忘记关闭文件

 

 

 

posted on 2010-10-17 20:49  John Smith  阅读(721)  评论(1编辑  收藏  举报