簡體   English   中英

使用“break”語句時循環不會中斷

[英]While loop not breaking even with the 'break' statement

我是 python 和一般編程的初學者,所以我不知道我的代碼有什么問題。 我試圖打破 while 循環,但它不起作用。 此外,斐波那契數字代碼也無法正常工作。 1 到 1000 之間的所有數字都被解釋為 FIB 數字。

import collections
import threading


def main():
    my_list = []
    i = 0
    time_second = int(input("Please input seconds\n"))

    def sample():
    threading.Timer(time_second, sample).start()
    # Counts the frequency of number in a list

    ctr = collections.Counter(my_list)
    print(ctr)

sample()

first_number = int(input("Please enter the first number\n"))
my_list.append(first_number)

while True:
    user_input = input("Enter number\n")
    

    if user_input.isnumeric():
        user_input = int(user_input)

        # check for Fibonacci number

        def fibonacci(n):
            if n == 1:
                return 1
            if n == 2:
                return 1
            elif n > 2:
                return fibonacci(n - 1) + fibonacci(n - 2)

    if user_input in range(1, 1001):
        print("FIB")

    my_list.append(user_input)

   if user_input == 'q':
        print("Bye")
        break


  main()

您的 function 位於一個奇怪的位置,我建議您將它放在 while 循環之外。

有幾種方法可以退出循環。 其中一種方法是滿足 while 循環退出的條件。

import time

def in_loop(count):
    print(f"Still in loop... on the {count} cycle")

def exited_the_loop():
    print("Exited the loop")

count = 0

while count < 10:
    time.sleep(.3)
    count += 1
    in_loop(count)

exited_the_loop()

另一種方法是在循環中滿足某個條件時使用python的break。 在這種情況下,我使用了 if 語句來檢查這種情況。

import time

def in_loop(count):
    print(f"Still in loop... on the {count} cycle")

def exited_the_loop():
    print("Exited the loop")

count = 0

while True:
    time.sleep(.3)
    count += 1
    in_loop(count)
    if count > 10:
        break
        
exited_the_loop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM