What is the method to break a loop in Python?
There are several ways to break a loop in Python.
- to fracture or shatter
- – fracture
while True:
x = input("请输入一个数字:")
if x == 'q':
break
else:
print("你输入的数字是:" + x)
If the user inputs the letter q in the example above, the loop will be terminated.
- keep going
- keep going
for i in range(10):
if i % 2 == 0:
continue
print(i)
In the example above, if i is an even number, then the continue statement will skip print(i) and go directly to the next iteration.
- come back
- come back
def find_num(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return -1
numbers = [2, 4, 6, 8, 10]
result = find_num(numbers, 6)
print(result)
In the given example, if the target number 6 is found, the loop will be interrupted and the index of that number will be returned using the return statement; otherwise, a return -1 will be executed to indicate that the target number was not found.