a = 2
b = 1;
print(a+b);
a = "0"
b = "1"
print(a+b)
python可以动态更改变量类型,而且使用非常方便
除法运算中的floor division与一般除法的区别比较:
print(3/4)
print(3./4)
print(3//4)
print(-3//4)
输出分别是:0; 0.75; 0; -1;
function 理解:
def myFunction(a):
print("entry: " + str(a))
a += 2
if a < 5:
myFunction(a)
elif a < 20:
a += 5
myFunction(a)
else:
a -= 1
print("exit: " + str(a))
myFunction(2)
输出:
for循环:
a = 10
for a in range(1,3):
print("a = "+ str(a))
字典类型:
myDictionary = {'first':'1st', 'second':'2nd', 'third':'3rd'}
print(myDictionary['second'])
for a in myDictionary:
print(a)
myDictionary['fourth']= '4th'
for a in myDictionary:
print(a, myDictionary[a])
输出:
异常处理:
var1 = '1'
try:
var2 = var1 + 1
except:
var2 = int(var1)+1
print(var2)
print("var2 = %d" % var2)
输出:2; var2 = 2;
在异常处理块内定义的变量,当做全局变量处理
简单文件读写操作:
f = open('test.txt', 'w')
f.write("This is my first text file created in Python.\n")
f.write("\t---by Sinjon.\n")
f.close()
f = open('test.txt', "r")
print(f.readline())
print(f.read(3))
print(f.read())
f.close()
f = open("test.txt", "a")
f.write("appending to a file")
f.close()
f = open("test.txt", "r")
myList = []
for line in f:
myList.append(line)
print(myList)
f.close()
输出:
类的使用:
class Calculator(object):
def __init__(self):
self.current = 0
print("initializing...")
print(self.current)
def add(self, amount):
print "adding..."
print("%d + %d" % (self.current, amount))
self.current += amount
def getCurrent(self):
return self.current
from ClassOne import *
myBuddy = Calculator()
myBuddy.add(10)
print(myBuddy.getCurrent())
输出
参考Tutorial:点击打开链接