三、条件判断和循环
3.1 if和else的用法
a=7
b=3.5
if isinstance(a,(int)) and isinstance(b,float):
… print a+b
… else:
… print “a and b are not same type”
…
10.5
例:输入一个数,用if和elif判断这个数的大小
a=raw_input(“请输入一个数:”)
请输入一个数:19type(a)
<type ‘str’> //注意输入的数据类型为strif int(a)==10: //把str类型强制转换成int类型才能比较大小
… print “equal”
… elif int(a)>10:
… print “big”
… else:
… print “less”
…
big
3.2 for循环
for i in range(1,34,3): //range函数
… print i
…
1
4
7
10
13
16
19
22
25
28
31
此处range:
range(1,34,3)开区间从1到33,每间隔3个数打印一次
例:打印从1到100的所有奇数
print range(1,101,2)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
3.3 while循环
//打印五个hi
a=5
while a>=1:
… print “hi”
… a=a-1
…
hi
hi
hi
hi
hi
例:用while循环输入三个单词,并连成一句话输出
result=" "
a=3
while a>=1:
… result=result+raw_input(“please input a word:”)
… result=result+""
… a=a-1
…
please input a word:hello
please input a word:world
please input a word:!print result
helloworld!