簡體   English   中英

while循環不在python中退出

[英]While-loop not exiting in python

我現在正在嘗試自學python,而且我正在使用“學習Python艱難之路”這樣的練習。

現在,我正在進行一個涉及while循環的練習,在那里我從腳本中獲取while循環,將其轉換為函數,然后在另一個腳本中調用該函數。 最終程序的唯一目的是將項添加到列表中,然后在列表中打印。

我的問題是,一旦我調用該函數,嵌入式循環決定無限繼續。

我已經多次分析了我的代碼(見下文),並且找不到任何明顯的錯誤。

def append_numbers(counter):
    i = 0
    numbers = []

    while i < counter:
        print "At the top i is %d" % i
        numbers.append(i)

        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

count = raw_input("Enter number of cycles: ")

print count
raw_input()

append_numbers(count)

我相信你想要這個。

count = int(raw_input("Enter number of cycles: "))

如果不將輸入轉換為整數,則最終會在count變量中輸入一個字符串,即如果在程序要求輸入時輸入1 ,則計數為'1'

字符串和整數之間的比較結果為False 因此, while i < counter:的條件總是為False因為i是一個整數,而counter是程序中的一個字符串。

在您的程序中,如果您使用了print repr(count)來檢查count變量中的值是什么,那么您可以自己調試它。 對於你的程序,當你輸入1時它會顯示'1' 。根據我建議的修正,它只顯示1

將輸入字符串轉換為整數... count=int(count)

以上已被清除為什么同時循環永遠。 它循環很多(= ASCII代碼真的很大)

但要解決這個問題你可以簡單地說:

while i<int(counter):
    print "At the top i is %d" % i
    numbers.append(i)

raw_input返回一個字符串,但i是一個整數。 嘗試使用input而不是raw_input

暫無
暫無

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

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