Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
for循环的语法格式如下:
for iterating_var in sequence:
statements(s)
-
基本使用
for item in 'Python': print(item) for item in ['zhangsan','lisi','wangwu']: print(item) for item in [1,2,3,4,5]: print(item) for item in range(10): print(item) for item in range(5,10,2): print(item)
-
for循环计算三个数的和:
prices=[10,20,30] total=0 for price in prices: total+=price print(f"Total:{total}")
-
嵌套循环:
for x in range(4): for y in range(3): print(f"({x},{y})")
-
编写一个程序,输出如下图示:
xxxxx
xx
xxxxx
xx
xxnumbers = [5,2,5,2,2] for x_count in numbers: output = '' for count in range(x_count): output+="x" print(output)