为什么有了while循环,还需要有for循环呢?不都是循环吗?for循环能够控制,而while不可控。
字典也有取多个值的需求,字典可能有while循环无法使用了,这个时候可以使用我们的for循环。
dic = {'name': 'wzh', 'age': 19} for i in dic: # 取出i的keys print(i) ''' name age '''简单遍历字典只能取出字典的key。下面是更骚的方法:
dic.items() # 取出字典的键值对 dic.key() # 取出字典的关键字 dic.value() # 取出字典的value值for循环的循环次数受限于容器类型的长度,而while循环的循环次数需要自己控制。for循环也可以按照索引取值。
# for循环按照索引取值 name_list = ['nick', 'jason', 'tank', 'sean'] for i in range(len(name_list)): print(i, name_list[i]) ''' 0 nick 1 jason 2 tank 3 sean '''range表示范围,顾头不顾尾,放在for循环里表示循环次数
range(5) # 0,1,2,3,4 range(1,5) # 1,2,3,4 for i in range(1,4): print(i) # 1,2,3与while + break一样,for循环跳出本层循环。
# for+break name_list = ['nick', 'jason', 'tank', 'sean'] for name in name_list: if name == 'jason': break print(name) # 终止循环,只打印上一次循环的'nick'for循环跳出本次循环,进入下一次循环
# for+continue name_list = ['nick', 'jason', 'tank', 'sean'] for name in name_list: if name == 'jason': continue print(name) # 跳出本次循环,打印'nick','tank','sean'外层循环循环一次,内层循环循环所有的。
# for循环嵌套 for i in range(3): print(f'-----:{i}') for j in range(2): print(f'*****:{j}') ''' -----:0 *****:0 *****:1 -----:1 *****:0 *****:1 -----:2 *****:0 *****:1 '''for循环没有break的时候触发else内部代码块。
# for+else name_list = ['nick', 'jason', 'tank', 'sean'] for name in name_list: print(name) else: print('for循环没有被break中断掉') ''' nick jason tank sean for循环没有break中断掉 '''/r可实现将打印结果覆盖上一次打印结果
# 进度条实例 import time scale = 10 print("执行开始".center(scale // 2, "-")) start = time.perf_counter() for i in range(scale + 1): a = '*' * i b = '.' * (scale - i) c = (i / scale) * 100 dur = time.perf_counter() - start print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c, a, b, dur), end='') time.sleep(0.1) print("\n" + "执行结束".center(scale // 2, '-')) ''' -执行开始 100%[**********->]1.03s -执行结束 '''转载于:https://www.cnblogs.com/dadazunzhe/p/11284719.html