Python break 和 continue
时间:2020-02-23 14:42:28 来源:igfitidea点击:
今天,我们将学习Python break和continue语句。
Python中断语句 和 继续语句
Python break和continue语句仅在循环中使用。
它有助于修改循环行为。
假设您正在执行循环,在一个阶段中,您需要终止循环或者跳过某些语句,然后需要这些语句。
Python中断
该语句用于中断循环。
假设您正在使用while循环打印奇数。
但是您不需要打印大于10的数字。
那么您可以编写以下python代码。
number = 1 #Number is initially 1 while True : #This means the loop will continue infinite time print (number) #print the number number+=2 #calculate next odd number # Now give the breaking condition if number > 10: break; #Breaks the loop if number is greater than ten print (number) #This statement won't be executed
在给定的示例中,您将看到中断后编写的语句将不会执行。
因此,此处将不会打印11。
Python break语句也可以在for循环中使用。
假设您要从列表中打印单词。
如果任何与" exit"相匹配的单词都不会被打印,则循环将终止。
以下python代码说明了这一想法。
words = ["rain", "sun", "moon", "exit", "weather"] for word in words: #checking for the breaking condition if word == "exit" : #if the condition is true, then break the loop break; #Otherwise, print the word print (word)
Python继续
Python的continue语句用于跳过循环语句并迭代到下一步。
例如,您要打印数字1到10。
您需要在步骤7跳过所有语句。
以下python代码说明了这种情况。
numbers = range(1,11) ''' the range(a,b) function creates a list of number 1 to (b-1) So, in this case it would generate numbers from 1 to 10 ''' for number in numbers: #check the skipping condition if number == 7: #this statement will be executed print("7 is skipped") continue #this statement won't be executed print ("This won't be printed") #print the values #for example: #2 is double of 1 print (number*2), print ("is double of"), print (number)
您可以为while循环做同样的事情。
假设您正在尝试打印从1到10的所有奇数值,那么解决该问题的python代码将是:
numbers = [ 1, 2, 4, 3, 6, 5, 7, 10, 9 ] pos = 0 #initial position is one while pos < len(numbers): #checking skipping condition if number is divisible by two, it is even if numbers[pos] % 2 == 0 : #increment the position by one pos = pos + 1 continue #print the odd number print (numbers[pos]) #increment the position by one pos = pos + 1