探索循环中的计数与筛选功能

📅 2026/8/27 13:30:56
探索循环中的计数与筛选功能
目录1.引言2.计数器3.数字相加4.过滤筛选1.引言在之前我们有讲过通过循环来比较大小现在我们将进一步探讨循环的作用2.计数器loop_time 0 print(before, loop_time) for the_num in [10,40,13,4,73,19]: loop_time loop_time 1 print(loop_time, the_num) print(after, loop_time) #before 0 #1 10 #2 40 #3 13 #4 4 #5 73 #6 19 #after 6怎么样很神奇吧我们设定初始值loop_time循环次数为每运行一次循环次数便会110加一40加一13加一4加一73加一19加一总共是6次这就是计数的方法3.数字相加如果我想运用计算机把好几个数字相加应该怎么办呢比如作业中的算术题一个月的开支拿笔算吗还是拿计算器一个一个捣呢我之前有提到过计算机就是用来帮助人类处理费时费力的重复性工作的所以关于这种事还是交给程序来完成吧count 0 print(before, count) for the_num in [10,40,13,4,73,19]: count count the_num print(count, the_num) print(after, count) # before 0 # 10 10 # 50 40 # 63 13 # 67 4 # 140 73 # 159 19 # after 159通过对代码进行简单的修改我们得出了一个可以计算数字总和的程序。在这个程序中我们将加法中的1替换为the_num每次循环都用count和the_num相加完成了总和的计算。好的让我们增加一些难度试着将计数加入进去看一看一共经历了几步运算首先请你自己试一试吧你可以的loop_time 0 count 0 print(before, loop_time, count) for the_num in [10,40,13,4,73,19]: count count the_num loop_time loop_time 1 print(loop_time, count, the_num) print(after, loop_time, count, count/loop_time) # before 0 0 # 1 10 10 # 2 50 40 # 3 63 13 # 4 67 4 # 5 140 73 # 6 159 19 # after 6 159 26.5我在这里还添加了平均数count/loop_time让代码有更多的可能性你可以自己尝试一下用变量名的方法概括替代count/loop_time4.过滤筛选接下来让我们讨论一下如何筛去集合中一些不满足条件的值我们用将循环结构来将集合过一遍print(before) for the_num in [10,40,13,4,73,19]: if the_num 20: print(Larger number, the_num) print(after) # before # Larger number 40 # Larger number 73 # after例如这段代码我们想要筛选出比20大的数字就添加加条件语句如果大于20则输出后循环如果不大于则直接循环10大于20吗不循环40大于20吗是的输出40接着循环13不输出4不输出73输出19不输出结束