5.1变量和表达式
例子5.1复利计算机(Simple Compound -Interest Calculation)
按照数字(int)类型输出:
<span style="font-size:18px;">import string
principal=1000 #Initial amount
rate =0.05 #Interest rate
numyears=5 #Number of years
year =1
while year <= numyears:
principal=principal*(1+rate)
print year ,principal
year+=1</span>
按照字符串(string)类型输出:
<span style="font-size:18px;">import string
principal=1000 #Initial amount
rate =0.05 #Interest rate
numyears=5 #Number of years
year =1
while year <= numyears:
principal=principal*(1+rate)
print str(year) +" " +str(principal)
year+=1</span>
输出结果:
<span style="font-size:18px;">1 1050.0
2 1102.5
3 1157.625
4 1215.50625
5 1276.2815625</span>
Python语言的动态特性。最初,它被赋值给principal,当赋值动作发生改变的时候,principal最初的绑定值1000被丢弃。赋值结束,不但principal绑定的值发生了变化,它的类型也随着赋值动作发生了相应的变化。在本例子中,由于rate是一个浮点数,principal最终也是一个浮点数。
Python中每个语句以换行结束,当然你也可以在一行中写多个语句,但是各个语句之间要用分号分隔。
principal=1000;rate=0.05; numyears=5;
为了有一个更好的输出格式,可以用格式控制符:
<span style="font-size:18px;">print "%3d %0.2f" %(year,principal)</span>
其中:%3d是将一个整数在宽度在宽度为3个字符的栏中右对齐,%0.2f 是将一个浮点数的小数点后部分转换为2位。
5.2 条件语句
<span style="font-size:18px;">a=10;b=60;
if a<b:
z=b
else:
z=a
print z</span>
可以通过or,and 和not关键字建立任意的条件表达式:
<span style="font-size:18px;">c=100
if a<=b and b<=c:
print "b is between a and c"
if not(b<a or b>c):
print "b is still btween a and c"</span>
用elif语句可以检验多重条件(可以用来代替其它语言中的switch语句)
<span style="font-size:18px;">a='+'
print a
if a=='+':
op='PLUS'
elif a=='-':
op='MINUS'
elif a=='*':
op='MULTLPLY'
else:
raise RuntimeError,"Unknown operator"
print op</span>
5.3字符串
字符串是一个以0开始,整数索引的字符序列,要获得字符串s中的第i+1个字符,可以使用索引操作符s[i]:
<span style="font-size:18px;">a='Hello world'
d=a[1]
print d</span>
最终的输出结果为字符:'e'
<span style="font-size:18px;">a='Hello world'
c=a[0:5]
d=a[6:]
e=a[3:8]
print a
print c
print d
print e
</span>
连接字符串:可以使用(+)
<span style="font-size:18px;">num = "1" # string type
num = "Let's go" # string type
num = "He's \"old\"" # string type
mail = """China:
hello
I am you!
""" # special string format
print mail
string = 'xiaoyi' # get value by index
copy = string[0] + string[1] + string[2:6] # note: [2:6] means [2 5] or[2 6)
print
copy = string[:4] # start from 1
copy = string[2:] # to end
copy = string[::1] # step is 1, from start to end
copy = string[::2] # step is 2
copy = string[-1] # means 'i', the last one
copy = string[-4:-2:-1] # means 'yoa', -1 step controls direction
</span>
5.4 列表和元组(Lists & Tuples)
就如同字符串是字符的序列,列表和元组则是任意对象的序列。元组tuple用()来定义。相当于一个可以存储不同类型数据的一个数组,可以通过索引来访问,但是需要注意的一点,里面的元素是不能被修改的。
例如:names=["zhang","wang","li","zhao"]
<span style="font-size:18px;">#列表
names=["zhang","wang","li","zhao"]
a=names[0]
names[0]="fu"
# len()函数用来得到列表的长度
print len(names)
#append() 在末尾添加新的元素
names.append("pan")
#insert(index,aMember)把元素插入的index之前的位置
names.insert(2,"zhou")
print names
#b返回 下标为0 1的值
b=names[0:2]
c=names[2:]
#利用(+)运算符连接列表
str1=[1,2,3]+[4,5]
print "+连接符"
print str1
#列表元素可以是任意的 python对象
str2=[1,"zjgs",3.14,["Mark",7,9,[100,101]],10]
print str2
print str2[1]
print str2[3][2]
print str2[3][3][1]
</span>
运行结果:
<span style="font-size:18px;">4
['fu', 'wang', 'zhou', 'li', 'zhao', 'pan']
+连接符
[1, 2, 3, 4, 5]
[1, 'zjgs', 3.14, ['Mark', 7, 9, [100, 101]], 10]
zjgs
9
101</span>
元组例子:
<span style="font-size:18px;">print "元组系列"
tup=(1,4,5,-9,10)
tup2=(7,) #添加一个额外的逗号
first_name="wang"
last_name="gang"
phone=123456789
person=(first_name,last_name,phone)
print tup
print tup2
print person</span>
5.5 循环
for循环,通过一个迭代序列来遍历元素。
<span style="font-size:18px;">#range(i,j)函数建立一个整数序列,从i开始到j为止(包括i,但是不包括j)
#若第一个被省略,则默认0,还可以有第三个参数,步进值
for i in range(1,10):
print "2 to the %d power is %d" %(i,2**i)
a=range(5)
print a
b=range(1,8)
print b
c=range(0,14,3)#步长为3
print c
stra="Hello world"
for strc in stra:
print strc
strd=["kjksjf","iuiukj","zjgs"]
# print the number of a list
for name in strd:
print name</span>
运行结果:
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7]
[0, 3, 6, 9, 12]
H
e
l
l
o
w
o
r
l
d
kjksjf
iuiukj
zjgs