What is the method to break a loop in Python?

There are several ways to break a loop in Python.

  1. to fracture or shatter
  2. – 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.

  1. keep going
  2. 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.

  1. come back
  2. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds