1. 程式人生 > >python 循環:for()、while()

python 循環:for()、while()

bsp cti tex int 操作 tuple ges bin 沒有

格式:

for 變量 in 列表:

while 表達式:


一、for循環

#!/usr/bin/python

#for [0..5]
sum = 0; #當我沒有初始化sum時,會提示TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'int'

for x in [0, 1, 2, 3, 4, 5]:
sum = sum + x;
print x, sum;
print sum;

技術分享圖片


#for [0..5]
sum = 0;
for x in range(6):
sum += x;

print x, sum;
print sum;

技術分享圖片

技術分享圖片


#for list/tuple
list = ['a', 'b', 'c', 'you'];
for list in list:
print list;

技術分享圖片


二、while循環

#!/usr/bin/python

n = 9
while n > 0:
print n;
n -= 1; #python不支持 ++/--操作

技術分享圖片


python 循環:for()、while()