[英]Why do my python program with while loop runs infinitely
這是正式的python文檔中給出的用於打印Fibonacci系列的代碼。
我不明白為什么在while循環條件還不錯的情況下,這段代碼為什么會運行到無窮大。
def fib(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a + b
number = raw_input("What's the number you want to get Fibonacci series up to?")
fib(number)
您正在將字符串傳遞給fib
,而a
是整數。 在Python 2中, 任何整數都小於任何字符串。
>>> 1000000000000000000000000000000000 < ""
True
>>> 3 < "2"
True
而是使用整數調用函數:
fib(int(number))
如果您使用的是Python 3,則嘗試比較字符串和數字只會引發TypeError
:
>>> "3" < 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
Raw_input提供了一個字符串,因此您將字符串與int進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.