[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"article-5":3},{"id":4,"title":5,"title_en":6,"abstract":7,"abstract_en":8,"content":9,"content_en":10,"category":11,"banner_id":12,"banner_path":13,"tags":14,"is_recommend":16,"prev_article":17,"next_article":21,"created_at":25},5,"python基础--循环语句","Python Basics - Loop Statements","在流程控制中，难免会有一些重复的工作，比如给100个变量复制，打印列表中的每一个元素等，如果都每一条语句都要我们自己进行操作，那工作量是非常大的","In process control, it is inevitable that there will be some repetitive work, such as copying 100 variables, printing every element in the list, etc., if we have to operate every sentence by ourselves, the workload is very large","在流程控制中，难免会有一些重复的工作，比如给100个变量复制，打印列表中的每一个元素等，如果都每一条语句都要我们自己进行操作，那工作量是非常大的\n\n在python中，有两个循环语句，`while`和`for` ，两个的原理类似，先判断条件，条件成立就执行循环体内的语句，然后再次判断条件是否成立，再次执行循环内的语句，直到条件不成立\n\n### while循环\n\n#### 语法\n\nPython 编程中 while 语句用于循环执行程序，即在某条件下，循环执行某段程序，以处理需要重复处理的相同任务。其基本形式为：\n\n```Python\nwhile 条件满足：\n    语句1...\nelse:\n    循环完成后 要执行的语句\n```\n\n执行语句可以是单个语句或语句块。判断条件可以是任何表达式，任何非零、或非空（null）的值均为true\n\n当判断条件为假（False）时，循环结束\n\n### 死循环\n\n当条件一直为真时会一直循环下去，一直在循环内，不能走出循环的语句，被称为“死循环”又叫“无限循环”\n\n```Python\n# 最简单的死循环语句\nwhile True:\n  print('这是一条死循环')\n```\n\n### 循环使用 else 语句\n\n在 python 中，while … else 在循环条件为 false 时执行 else 语句块：\n\n```Python\ncount = 0\nwhile count &lt; 5:\n   print (count, \" is  less than 5\")\n   count = count + 1\nelse:\n   print (count, \" is not less than 5\") \n```\n\n条件成立时，执行第一个print语句，然后count+1，直到count加到5，条件不满足，执行else下的print语句\n\n可用于判断循环结构是否结束\n\n### 简单语句组\n\n类似 if 语句的语法，如果你的 while 循环体中只有一条语句，你可以将该语句与while写在同一行中， 如下所示：\n\n```Python\nflag = 1\nwhile (flag): print 'Given flag is really true!'\nprint \"Good bye!\"\n```\n\n使用while循环计算1+2+......+99+100的值：\n\n```Python\ni=1\nsum=0\nwhile i&lt;=100:\n    sum+=i\n    i+=1\nprint(sum)\n# 5050 \n```\n\n### for循环\n\n它常用于遍历字符串、列表、元组、字典、集合等序列类型，逐个获取序列中的各个元素\n\nfor 循环的语法格式如下：\n\n```Python\nfor 迭代变量 in 字符串|列表|元组|字典|集合:\n  代码块\n```\n\n格式中，迭代变量用于存放从序列类型变量中读取出来的元素，所以一般不会在循环中对迭代变量手动赋值\n\n代码块指的是具有相同缩进格式的多行代码（和 while 一样），由于和循环结构联用，因此代码块又称为循环体\n\n```Python\nadd = \"https:\u002F\u002Fwww.baidu.com\"\n#for循环，遍历 add 字符串\nfor ch in add:\n    print(ch,end=\"\")\n# 输出：https:\u002F\u002Fwww.baidu.com\n```\n\n可以看到，使用 for 循环遍历  add 字符串的过程中，迭代变量 ch 会先后被赋值为 add 字符串中的每个字符，并代入循环体中使用。只不过例子中的循环体比较简单，只有一行输出语句\n\n实现计算1+2+......+99+100的值\n\n```Python\nprint(\"计算 1+2+...+100 的结果为：\")\n#保存累加结果的变量\nresult = 0\n#逐个获取从 1 到 100 这些值，并做累加操作\nfor i in range(101):\n    result += i\nprint(result)\n# 计算 1+2+...+100 的结果为：\n# 5050 \n```\n\n这个时候，在我们的代码里面出现了一个陌生的函数——range( )函数\n\n### range( ) 的使用\n\n上面代码中，使用了 range() 函数，此函数是 Python 内置函数，用于生成一系列连续整数，多用于 for 循环中\n\n我们这里只需要明白range() 函数可以进行数字迭代生成就好了\n\n### for循环遍历列表和元组\n\n当用 for 循环遍历 list 列表或者 tuple 元组时，其迭代变量会先后被赋值为列表或元组中的每个元素并执行一次循环体\n\n```Python\n# 对列表进行遍历\nmy_list = [1,2,3,4,5]\nfor ele in my_list:\n    print('ele =', ele) \n     \n```\n\n&gt; ele = 1\nele = 2\nele = 3\nele = 4\nele = 5\n\n```Python\n# 对元组进行遍历\nmy_list = (1,2,3,4,5)\nfor ele in my_list:\n    print('ele =', ele)\n     \n```\n\n可以看到两者结果是完全相同的\n\n&gt; ele = 1\nele = 2\nele = 3\nele = 4\nele = 5\n\n\n\n### for 循环遍历字典\n\n在使用 for 循环遍历字典时，经常会用到和字典相关的 3 个方法，即 items()、keys() 以及 values()，它们各自的用法已经在前面章节中讲过，这里不再赘述。当然，如果使用 for 循环直接遍历字典，则迭代变量会被先后赋值为每个键值对中的键。\n\n```Python\ndic={'name':'小明','age':22,'score':100}\nfor di in dic:\n    print(di)\n# 得到字典的每一个键（key）默认\nfor di in dic.items():\n    print(di)\n# 得到字典的每一组数据，其结果为一个元组\nfor di in dic.values():\n    print(di)\n# 得到字典的每一组键所对应的值    \nfor di in dic.keys():\n    print(di)\n#得到字典的每一键（key） 默认情况\n```\n\n字典中的items( )、keys( ) 以及 values ( ) 的用法\n\nitems()：以列表返回可遍历的(键, 值) 元组数组\n\nitems() 方法的遍历：items() 方法把字典中每对 key 和 value 组成一个元组，并把这些元组放在列表中返回\n\n```Python\nd = {'one': 1, 'two': 2, 'three': 3}\n&gt;&gt;&gt; d.items()\ndict_items([('one', 1), ('two', 2), ('three', 3)])\n&gt;&gt;&gt; type(d.items())\n\n\n&gt;&gt;&gt; for key,value in d.items():#当两个参数时\n    print(key + ':' + str(value))\none:1\ntwo:2\nthree:3\n\n&gt;&gt;&gt; for i in d.items():#当参数只有一个时\n    print(i)\n('one', 1)\n('two', 2)\n('three', 3)\n```\n\nkeys()：以列表返回一个字典所有的键\n\nvalues()：以列表返回一个字典所有的值\n\n### for练习\n\n- 求1～100内偶数之和\n\n```Python\nsum = 0\nfor i in range(2,101,2):\n    sum += i\nprint(sum)\n```\n\n- 求阶乘\n\n```Python\n# 求阶乘\nnum = int(input('请输入一个数字：'))\nres = 1\nfor i in range(1, num + 1):   \n  res*=i\nprint('%d的阶乘为：%d' %(num,res))\n```\n\n- 9*9乘法表\n\n```Python\nfor i in range(1,10):\n    for j in range(1,i+1):\n            print('%d * %d = %d\\t' %(i,j,i*j),end='')\n    print()\n```\n\n- 求最大公约数和最小公倍数\n\n```Python\n# 输入两个数字\nnum1=int(input('Num1：'))\nnum2=int(input('Num2：')) \n# 找出两个数中的较小者\nmin_num = min(num1,num2) \n# 确定最大公约数\nfor i in range(1,min_num+1):    \n    if num1 % i ==0 and num2 % i ==0:        \n        max_commer = i\n# 求最小公倍数\nmin_commer =int(num1 * num2)\u002Fmax_commer \nprint('%s 和 %s 的最大公约数为%s' %(num1,num2,max_commer))\nprint('%s 和 %s 的最小公倍数为%s' %(num1,num2,min_commer))\n```\n\n\n\n### break的使用\n\nPython break语句，就像在C语言中，打破了最小封闭for或while循环。\n\nbreak语句用来终止循环语句，即循环条件没有False条件或者序列还没被完全递归完，也会停止执行循环语句。\n\nbreak语句用在`while`和`for`循环中。\n\n如果您使用嵌套循环，break语句将停止执行最深层的循环，并开始执行下一行代码。\n\n---\n\n我们知道，在执行 while 循环或者 for 循环时，只要循环条件满足，程序将会一直执行循环体，不停地转圈。但在某些场景，我们可能希望在循环结束前就手动离开循环，Pyhton&nbsp;提供了 2 种强制离开当前循环体的办法：\n\n1. 使用 continue 语句，可以跳过执行本次循环体中剩余的代码，转而执行下一次的循环。\n2. 只用 break 语句，可以完全终止当前循环。\n\n我们先来了解`break`语句\n\n在某些场景中，如果需要在某种条件出现时强行中止循环，而不是等到循环条件为 False 时才退出循环，就可以使用 break 来完成这个功能。\n\nbreak 用于完全结束一个循环，跳出循环体。不管是哪种循环，一旦在循环体中遇到 break，系统就将完全结束该循环，开始执行循环之后的代码。\n\n\n\n这就好比在操场上跑步，原计划跑 10 圈，可是当跑到第 2 圈的时候，突然想起有急事要办，于是果断停止跑步并离开操场，这就相当于使用了 break 语句提前终止了循环。\n\nbreak 语句一般会结合 if 语句进行搭配使用，表示在某种条件下，跳出循环体，如果使用嵌套循环，break 语句将跳出当前的循环体。\n\nbreak 语句的语法非常简单，只需要在相应 while 或 for 语句中直接加入即可。例如如下程序：\n\n```Python\n# 一个简单的for循环\nfor i in range(0, 10) :\n    print(\"i的值是: \", i)\n    if i == 2 :\n        # 执行该语句时将结束循环\n        break\n```\n\n当i等于2时系统结束循环\n\nbreak 语句导致了 i==2 时执行结束，因为当 i==2 时，在循环体内遇到了 break 语句，程序跳出该循环。  \n\n需要注意的是，对于带 else 块的 for 循环，如果使用 break 强行中止循环，程序将不会执行 else 块。例如如下程序：\n\n```Python\n# 一个简单的for循环\nfor i in range(0, 10) :\n    print(\"i的值是: \", i)\n    if i == 2 :\n        # 执行该语句时将结束循环\n        break\nelse:\n    print('else块: ', i) # 这个else语句并不会执行\n```\n\n上面程序同样会在 i==2 时跳出循环，而且此时 for 循环不会执行 else 块。\n\n在使用 break 语句的情况下，循环的 else 代码块与直接放在循环体后是有区别的，即如果将代码块放在 else 块中，当程序使用 break 中止循环时，循环不会执行 else 块；如果将代码块直接放在循环体后面，当程序使用 break 中止循环时，程序自然会执行循环体之后的代码块。\n\n另外，针对嵌套的循环结构来说，Python 的 break 语句只能结束其所在的循环体，而无法结束嵌套所在循环的外层循环。例如：\n\n```Python\nfor i in range(0,4) :\n    print(\"此时 i 的值为：\",i)\n    for j in range(5):\n        print(\"    此时 j 的值为:\",j)\n        break\n    print(\"跳出内层循环\")\n```\n\n分析运行结果不难看出，每次执行内层循环体时，第一次循环就会遇到 break 语句，即做跳出所在循环体的操作，转而执行外层循环体的代码。\n\n如果想达到 break 语句不仅跳出单前所在循环，同时跳出外层循环的目的，可先定义 bool 类型的变量来标志是否需要跳出外层循环，然后在内层循环、外层循环中分别使用两条 break 语句来实现。例如如下程序：\n\n```Python\nexit_flag = False\n# 外层循环\nfor i in range(0, 5) :\n    # 内层循环\n    for j in range(0, 3 ) :\n        print(\"i的值为: %d, j的值为: %d\" % (i, j))\n        if j == 1 :\n            exit_flag = True\n            # 跳出里层循环\n            break\n    # 如果exit_flag为True，跳出外层循环\n    if exit_flag :\n        break  \n\n```\n\n上面程序在内层循环中判断 j 是否等于 i，当 j 等于 i 时，程序将 exit_flag 设为 True，并跳出内层循环；接下来程序开始执行外层循环的剩下语句，由于 exit_flag 为 True，因此也会执行外层循环的 break 语句来跳出外层循环。\n\n程序从外层循环进入内层循环后，当 j 等于 i 时，程序将 exit_flag 设为 True，并跳出内层循环；接下来程序又执行外层循环的 break 语句，从而跳出外层循环。\n\n### continue的使用\n\n和 break 语句相比，continue 语句的作用则没有那么强大，它只会终止执行本次循环中剩下的代码，直接从下一次循环继续执行。\n仍然以在操作跑步为例，原计划跑 10 圈，但当跑到 2 圈半的时候突然接到一个电话，此时停止了跑步，当挂断电话后，并没有继续跑剩下的半圈，而是直接从第 3 圈开始跑。\ncontinue 语句的用法和 break 语句一样，只要 while 或 for 语句中的相应位置加入即可。例如：\n\n```Python\nadd = \"https:\u002F\u002Fbaidu.com,https:\u002F\u002Fzhihu.com\"\n# 一个简单的for循环\nfor i in add:\n    if i == ',' :\n        # 忽略本次循环的剩下语句\n        print('\\n')\n        continue\n    print(i,end=\"\")\n#  https:\u002F\u002Fbaidu.com\nhttps:\u002F\u002Fzhihu.com\n```\n\n程序在遇到 ' ,' 时，跳过本次循环，进行下一次循环\n\n#### continue的作用\n\n结合异常处理（try），查找异常报告并跳过这次异常\n\n\n\n### range使用\n\nrange语法\n\n```Python\nrange(start,stop,step)\n```\n\n&gt; start：开始\nstop：结束（stop值是不包含的）\nstep：步长\n\npython2.x range() 函数可创建一个整数列表，一般用在 for 循环中\n\n注意：Python3 range() 返回的是一个可迭代对象（类型是对象），而不是列表类型， 所以打印的时候不会打印列表，具体可查阅 [Python3 range()](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#range) 用法说明。\n`print(range(1,100),type(range(1,100)))`\n`# range(1, 100) `\n我们可用使用list函数返回列表\n\n```Python\nprint(list(range(1,10)))\n# [1, 2, 3, 4, 5, 6, 7, 8, 9] \n```\n\n一些range对象的例子\n\n&gt;  list(range(10))\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist(range(1, 11))\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n list(range(0, 30, 5))\n[0, 5, 10, 15, 20, 25]\n list(range(0, 10, 3))\n[0, 3, 6, 9]\n list(range(0, -10, -1))\n[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n list(range(0))\n[] \nlist(range(1, 0))\n[]\n\nrange 对象实现了 一般 序列的所有操作，但拼接和重复除外（这是由于 range 对象只能表示符合严格模式的序列，而重复和拼接通常都会违反这样的模式）\n\n[`range`](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#range) 类型相比常规 [`list`](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#list) 或 [`tuple`](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#tuple) 的优势在于一个 [`range`](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#range) 对象总是占用固定数量的（较小）内存，不论其所表示的范围有多大（因为它只保存了 `start`, `stop` 和 `step` 值，并会根据需要计算具体单项或子范围的值）\n\nrange 对象实现了 collections.abc.Sequence ABC，提供如包含检测、元素索引查找、切片等特性，并支持负索引\n\n```Python\nr = range(0, 20, 2)\n# 0 2 4 6 8 10 12 14 16 18 \n```\n\n```\n&gt;&gt; r\nrange(0, 20, 2)\n&gt;&gt; 11 in r  #包含检测\nFalse\n&gt;&gt; 10 in r\nTrue\n&gt;&gt; r.index(10) # 根据内容查索引值\n5\n&gt;&gt; r[5]  # 根据索引查内容值\n10\n&gt;&gt; r[:5]  # 切片返回类一个新的range对象\nrange(0, 10, 2)\n&gt;&gt; r[-1]  # 取最后一个元素，是在range(0,20,2)上面进行的\n18\n```\n\n[while循环](https:\u002F\u002Fwww.wolai.com\u002FjAADGpGH99vaQjNkA15fzF)","In process control, it is inevitable that there will be some repetitive work, such as copying 100 variables, printing every element in the list, etc., if we have to operate every sentence by ourselves, the workload is very large\n\n>> r[-1] # takes the last element, which is done on top of range(0,20,2).\n\nIn Python, there are two loop statements, 'while' and 'for', the principle of the two is similar, first judge the condition, execute the statement in the loop if the condition is true, then judge whether the condition is true, and execute the statement in the loop again until the condition is not true\n\n### While loop\n\n#### Syntax\n\nIn Python programming, the while statement is used to execute a program in a loop, that is, under certain conditions, a certain segment of the program is executed in a loop to handle the same task that needs to be processed repeatedly. Its basic form is:\n```Python\nwhile condition is met:\nStatement 1...\nelse:\nThe statement to be executed after the loop is complete\n\n```\n\nAn execution statement can be a single statement or a block of statements. The judgment condition can be any expression, and any non-zero or non-null value is true\n\nWhen the judgment condition is False, the loop ends\n\n### Dead Loop\n\nWhen the condition is always true, it will continue to cycle, and it will always be in the loop, and the statement that cannot get out of the cycle is called \"dead loop\" or \"infinite loop\"\n```Python\n# The simplest dead loop statement\nwhile True:\nprint('It's a dead loop')\n\n```\n\n### Cycle through else statements\n\nIn python, while ... else executes the else statement block when the loop condition is false:\n```Python\ncount = 0\nwhile count \u003C 5:\nprint (count, \" is  less than 5\")\ncount = count + 1\nelse:\nprint (count, \" is not less than 5\")\n\n```\n\nWhen the condition is true, execute the first print statement, then count+1 until the count is added to 5, and if the condition is not satisfied, execute the print statement under else\n\nIt can be used to determine whether the loop structure is over\n\n### Simple statement sets\n\nSimilar to the syntax of an if statement, if you have only one statement in your while loop, you can write that statement on the same line as while, like this:\n```Python\nflag = 1\nwhile (flag): print 'Given flag is really true!'\nprint \"Good bye!\"\n\n```\n\nUse the while loop to calculate the value of 1+2+......+99+100:\n```Python\ni=1\nsum=0\nwhile i\u003C=100:\nsum+=i\ni+=1\nprint(sum)\n# 5050\n\n```\n\n### for loop\n\nIt is commonly used to iterate through sequence types such as strings, lists, tuples, dictionaries, collections, etc., to obtain individual elements in the sequence one by one\n\nThe syntax format for loop is as follows:\n```Python\nfor iterative variable in string|list|tuple|dictionary|collection:\nCode blocks\n\n```\n\nIn format, iterative variables are used to store elements read from sequence-type variables, so iteration variables are generally not manually assigned in a loop\n\nA code block is a multi-line code with the same indentation format (like while), which is also called a loop because it is coupled with a loop structure\n```Python\nadd = \"https:\u002F\u002Fwww.baidu.com\"\n#for 循环, iterate through the add string\nfor ch in add:\nprint(ch,end=\"\")\n# Output: https:\u002F\u002Fwww.baidu.com\n\n```\n\nAs you can see, when using a for loop to traverse the add string, the iterative variable ch is assigned to each character in the add string and substituted into the loop. However, the loop body in the example is relatively simple, with only one output statement\n\nImplement the calculation of values of 1+2+......+99+100\n```Python\nprint(\"The result of calculating 1+2+...+100 is:\")\n#保存累加结果的变量\nresult = 0\n#逐个获取从 these values from 1 to 100 and add them up\nfor i in range(101):\nresult += i\nprint(result)\n# The result of calculating 1+2+...+100 is:\n# 5050\n\n```\n\nAt this time, an unfamiliar function appeared in our code - the range( ) function\n\n### Use of range( ).\n\nIn the above code, the range() function is used, which is a Python built-in function used to generate a series of continuous integers, mostly used in for loops\n\nWe just need to understand that the range() function can be iteratively generated\n\n### for loop through lists and tuples\n\nWhen a list or tuple tuple is iterated through a for loop, its iterative variables are assigned to each element in the list or tuple and execute the loop once\n```Python\n# Traverse the list\nmy_list = [1,2,3,4,5]\nfor ele in my_list:\n     \nprint('ele =', ele)\n\n```\n> ele = 1\nele = 2\nele = 3\nele = 4\n\nele = 5\n```Python\n# Traverse the tuple\nmy_list = (1,2,3,4,5)\nfor ele in my_list:\n     \nprint('ele =', ele)\n\n```\n\nYou can see that the results are exactly the same for both\n> ele = 1\nele = 2\nele = 3\nele = 4\n\n\n\nele = 5\n\n### for Loop through the dictionary\n\nWhen using a for loop to traverse a dictionary, three dictionary-related methods are often used, namely items(), keys(), and values(), each of which has been discussed in the previous section and will not be repeated here. Of course, if you use a for loop to traverse the dictionary directly, the iterative variables will be assigned to the keys in each key-value pair.\n```Python\ndic={'name':'Xiao Ming','age':22,'score':100}\nfor di in dic:\nprint(di)\n# Get the default for each key in the dictionary\nfor di in dic.items():\nprint(di)\n# Get each set of data in the dictionary, the result of which is a tuple\nfor di in dic.values():\nprint(di)\n# Get the value corresponding to each set of keys in the dictionary\nfor di in dic.keys():\nprint(di)\n#得到字典的每一键(key) default\n\n```\n\nThe usage of items( ), keys( ) and values ( ) in the dictionary\n\nitems(): Returns an array of tuples that can be traversed (key, value) as a list\n\nTraversal of items() method: The items() method forms a tuple for each pair of key and value in the dictionary and returns it in a list\n```Python\nd = {'one': 1, 'two': 2, 'three': 3}\n>>> d.items()\ndict_items([('one', 1), ('two', 2), ('three', 3)])\n\n\n>>> type(d.items())\n>>> for key,value in d.items():#当两个参数时\nprint(key + ':' + str(value))\none:1\ntwo:2\n\nthree:3\n>>> for i in d.items(): #当参数只有一个时\nprint(i)\n('one', 1)\n('two', 2)\n('three', 3)\n\n```\n\nkeys(): Returns all keys in a dictionary as a list\n\nvalues(): Returns all values in a dictionary as a list\n\n### for practice\n\n- Find the sum of even numbers within 1~100\n```Python\nsum = 0\nfor i in range(2,101,2):\nsum += i\nprint(sum)\n\n```\n\n- Find factorials\n```Python\n# Find factorial\nnum = int(input('Please enter a number:'))\nres = 1\nfor i in range(1, num + 1):\nres*=i\nprint(factorial of '%d:%d' %(num,res))\n\n```\n\n- 9*9 multiplication table\n```Python\nfor i in range(1,10):\nfor j in range(1,i+1):\nprint('%d * %d = %d\\t' %(i,j,i*j),end='')\nprint()\n\n```\n\n- Find the greatest common divisor and least common multiple\n```Python\n# Enter two numbers\nnum1=int(input('Num1：'))\nnum2=int(input('Num2：'))\n# Find the smaller of the two numbers\nmin_num = min(num1,num2)\n# Determine the greatest common divisor\nfor i in range(1,min_num+1):\nif num1 % i ==0 and num2 % i ==0:\nmax_commer = i\n# Find the least common multiple\nmin_commer =int(num1 * num2)\u002Fmax_commer\nprint('%s and %s greatest common divisor is %s' %(num1,num2,max_commer))\nprint('The minimum common multiple of %s and %s is %s' %(num1,num2,min_commer))\n\n\n\n```\n\n### Use of break\n\nPython break statements, like in C, break the minimum closed for or while loop.\n\nThe break statement is used to terminate the loop statement, that is, if the loop condition does not have a false condition or the sequence has not been fully recursive, the execution of the loop statement will also be stopped.\n\nThe break statement is used in the 'while' and 'for' loops.\n\nIf you use nested loops, the break statement will stop executing the deepest loop and start executing the next line of code.\n\n---\n\nWe know that when executing a while loop or for loop, the program will continue to execute the loop body as long as the loop conditions are met. However, in some scenarios, we may want to manually leave the loop before the loop ends, and Pyhton&nbsp;provides 2 ways to force the current loop to leave:\n1. Use the continue statement to skip executing the remaining code in the loop and execute the next loop instead.\n\n2. Use only the break statement to completely terminate the current loop.\n\nLet's first understand the 'break' statement\n\nIn some scenarios, break can be used to accomplish this function if you need to forcibly abort a loop when a condition occurs, rather than waiting until the loop condition is False to exit the loop.\n\n\n\nBreak is used to completely end a loop and jump out of the loop. Regardless of the loop, once a break is encountered in the loop, the system will completely end the loop and start executing the code after the loop.\n\nThis is like running on the playground, originally planning to run 10 laps, but when it comes to the second lap, you suddenly remember that there is an urgent matter to do, so you decisively stop running and leave the playground, which is equivalent to using the break statement to end the loop early.\n\nThe break statement is generally used in conjunction with the if statement, indicating that under certain conditions, the break statement will jump out of the current loop, and if a nested loop is used, the break statement will jump out of the current loop.\n\nThe syntax of the break statement is very simple, just add it directly to the corresponding while or for statement. For example, the following procedure:\n```Python\n# A simple for loop\nfor i in range(0, 10) :\nprint(\"The value of i is: \", i)\nif i == 2 :\n# The loop ends when the statement is executed\nbreak\n\n```\n\nThe system ends the loop when i is equal to 2\n\nThe break statement causes the execution to end when i==2 because when i==2, a break statement is encountered in the loop and the program jumps out of the loop.\n\nNote that for a loop with an else block, if you use break to forcibly abort the loop, the program will not execute the else block. For example:\n```Python\n# A simple for loop\nfor i in range(0, 10) :\nprint(\"The value of i is: \", i)\nif i == 2 :\n# The loop ends when the statement is executed\nbreak\nelse:\nprint('else block: ', i) # This else statement is not executed\n\n```\n\nThe above program will also jump out of the loop at i==2, and the for loop will not execute else blocks at this time.\n\nIn the case of using a break statement, there is a difference between a loop's else block and a loop directly after the loop, i.e., if you place a code block in an else block, the loop will not execute the else block when the program aborts the loop using break; if the code block is placed directly behind the loop body, when the program uses break to abort the loop, the program will naturally execute the code block after the loop.\n\nIn addition, for nested loop structures, Python's break statement can only end the loop body in which it resides, but cannot end the outer loop of the nested loop. For example:\n```Python\nfor i in range(0,4) :\nprint(\"The value of i is:\",i)\nfor j in range(5):\nprint(\" The value of j is:\",j)\nbreak\nprint(\"Jump out of the inner loop\")\n\n```\n\nIt is not difficult to see that every time the inner loop is executed, the first loop will encounter a break statement, that is, do the operation of jumping out of the loop and execute the code of the outer loop instead.\n\nIf you want to achieve the goal of not only jumping out of the loop before the single but also jumping out of the outer loop, you can first define a variable of the bool type to indicate whether you need to jump out of the outer loop, and then use two break statements in the inner loop and the outer loop respectively. For example, the following program:\n```Python\nexit_flag = False\n# Outer circulation\nfor i in range(0, 5) :\n# Inner Circulation\nfor j in range(0, 3 ) :\nprint(\"i has a value: %d, j has a value: %d\" % (i, j))\nif j == 1 :\nexit_flag = True\n# Jump out of the inner loop\nbreak\n# If the exit_flag is True, it jumps out of the outer loop\nif exit_flag :\n\nbreak\n\n```\n\nThe above program determines whether j is equal to i in the inner loop, and when j is equal to i, the program sets exit_flag to True and jumps out of the inner loop. Next, the program starts executing the rest of the outer loop, and since exit_flag is true, it will also execute the break statement of the outer loop to jump out of the outer loop.\n\nAfter the program enters the inner loop from the outer loop, when j is equal to i, the program sets exit_flag to True and jumps out of the inner loop. Next, the program executes the break statement of the outer loop, thus jumping out of the outer loop.\n\n### Use of continue\nCompared to the break statement, the continue statement is less powerful and will only terminate the execution of the remaining code in the current loop and continue directly from the next loop.\nStill taking the operation run as an example, I originally planned to run 10 laps, but when I ran 2 and a half laps, I suddenly received a call, at this time I stopped running, and when I hung up the phone, I did not continue to run the remaining half lap, but started directly from the 3rd lap.\n\nThe use of the continue statement is the same as that of the break statement, as long as it is added to the corresponding position in the while or for statement. For example:\n```Python\nadd = \"https:\u002F\u002Fbaidu.com,https:\u002F\u002Fzhihu.com\"\n# A simple for loop\nfor i in add:\nif i == ',' :\n# Ignore the rest of the loop\nprint('\\n')\ncontinue\nprint(i,end=\"\")\n#  https:\u002F\u002Fbaidu.com\nhttps:\u002F\u002Fzhihu.com\n\n```\n\nWhen the program encounters ',', it skips this cycle and proceeds to the next loop\n\n#### The role of continue\n\n\n\nCombined with exception handling (try), find the exception report and skip the exception\n\n### range is used\n\nrange syntax\n```Python\nrange(start,stop,step)\n\n```\n> start: Start\nstop: end (stop value is not included)\n\nstep: step length\n\npython2.x range() function creates a list of integers, which is commonly used in for loops\nNote: Python3 range() returns an iterable object (type is an object), not a list type, so the list will not be printed when printing, please refer to the usage instructions of [Python3 range()](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#range).\n`print(range(1,100),type(range(1,100)))`\n`# range(1, 100) `\n\nWe can use the list function to return the list\n```Python\nprint(list(range(1,10)))\n# [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n```\n\nSome examples of range objects\n>  list(range(10))\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nlist(range(1, 11))\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nlist(range(0, 30, 5))\n[0, 5, 10, 15, 20, 25]\nlist(range(0, 10, 3))\n[0, 3, 6, 9]\nlist(range(0, -10, -1))\n[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\nlist(range(0))\n[]\nlist(range(1, 0))\n\n[]\n\nThe range object implements all operations of the normal sequence, except for splicing and repeating (this is because the range object can only represent sequences that conform to a strict pattern, and both duplication and stitching usually violate such a pattern)\n\n[`range`] The advantage of the (https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#range) type over the regular ['list'](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#list) or ['tuple'](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#tuple) is that a ['range'](https:\u002F\u002Fdocs.python.org\u002Fzh-cn\u002F3\u002Flibrary\u002Fstdtypes.html?highlight=range#range) object always takes up a fixed amount of (smaller) memory, regardless of the range it represents (because it only holds the 'start', 'stop' and 'step' values, and calculates the values of specific individual items or sub-ranges as needed)\n\nrange object implements collections.abc.Sequence ABC, which provides features such as inclusion detection, element index lookup, slicing, and supports negative indexing\n```Python\nr = range(0, 20, 2)\n# 0 2 4 6 8 10 12 14 16 18\n\n```\n```\n>> r\nrange(0, 20, 2)\n>> 11 in r #包含检测\nFalse\n>> 10 in r\nTrue\n>> r.index(10) # Check the index value according to the content\n5\n>> r[5] # Check the content value according to the index\n10\n>> r[:5] # slice returns a new range object in the class\nrange(0, 10, 2)\n18\n```\n\n[while loop] (https:\u002F\u002Fwww.wolai.com\u002FjAADGpGH99vaQjNkA15fzF)","python",0,"https:\u002F\u002Fblog4-1316398321.cos.ap-nanjing.myqcloud.com\u002Fblog5\u002F20250712011713__【哲风壁纸】汽车-草原.png",[15],"Python",false,{"id":18,"title":19,"title_en":20},4,"Python条件语句","Python conditional statements",{"id":22,"title":23,"title_en":24},6,"关于","Uncle Sam's blog","2025-07-21T05:02:38+08:00"]