虽然循环不会中断,但即使使用"break"语句也不会中断



我是python和编程的初学者,所以我不知道我的代码出了什么问题。我试图打破while循环,但它不起作用。此外,fibonacci数字代码也不能正常工作。1到1000之间的所有数字都被解释为FIB数字。

import collections
import threading

def main():
my_list = []
i = 0
time_second = int(input("Please input secondsn"))
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 numbern"))
my_list.append(first_number)
while True:
user_input = input("Enter numbern")

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()

您的函数位于一个奇怪的位置,我建议您将其放置在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()

最新更新