Python快速入门
时间:2010-10-17 来源:Aixe
# 注释
# This is a annotation
print("The length of (%s) is %d" %(v, len(v)))
print("dec: %d, oct: %o, hex: %x, float: %5f" %(64,64,64,64))
print(str(sum) + " dollas")
print(int(fund) + 1500)
print(ls)
print(ls[0])
print(dic)
print(dic[1])
for v in ls: print(v)
for k in dic: print("%s: %s" %(str(k), dic[k]))
for i in r1: print(i)
r2 = range(-1,-20,-2) # 从-1到-20(不包括-20),步长为-2
for j in r2: print(j)
if x==0:
print("zero")
elif x<0:
print("negative")
else:
print("positive")
def inc(a, b=0): return a + b;
print(sum(1, 99)) # return 100
print(inc(1, 99)) # return 100
print(inc(100)) # return 100
if s=="":
raise Exception("You must input something...")
try:
print(int(s))
except Exception as err:
print(err)
finally:
print("Bye Bye!")
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() # 表忘记关闭文件
# 变量和赋值
v = "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 = 2000print(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),步长为1for i in r1: print(i)
r2 = range(-1,-20,-2) # 从-1到-20(不包括-20),步长为-2
for j in r2: print(j)
# 条件判断
x = 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(1, 99)) # return 100
print(inc(1, 99)) # return 100
print(inc(100)) # return 100
# 异常处理
s = 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 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]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() # 表忘记关闭文件
相关阅读 更多 +