我目前在我的大學初學者的Python課程。我的作業部分是創建一個類似着名兒童歌曲「99瓶流行音樂」的節目。任務是:Python上的作業,麻煩與循環
- 用戶輸入一個項目。
- 該程序打印出如下陳述:「在牆上彈出x瓶,彈出x瓶,取下一個,通過它,(x-1)瓶在牆上彈出」直到它達到0 一旦達到0,程序必須停下來,並說牆上沒有瓶子彈出。
- 上限爲99。如果用戶輸入任何超過99,則顯示一個錯誤並迫使計數器開始在99
有道理正確?所以,這裏是我的代碼:
#Bottles of Pop on the Wall
#User inputs a number to start with
#Program returns with singing the popular song down to 0
#
print("Bottles of Pop on the Wall Program")
userBottle = int(input("How many bottles? "))
bottleCount = userBottle
while bottleCount > 1:
newBottle = userBottle - 1
bottleCount -= 1
if bottleCount > 99:
print("ALERT: no more than 99 bottles allowed, reverting to 99 bottles")
userBottle = 99
bottleCount = 99
newBottle = 99
print(userBottle , "bottles of pop on the wall, ", userBottle , "bottles of pop" ,
"\ntake one down, pass it around, " , newBottle , "bottles of pop on the wall")
userBottle -= 1
if bottleCount == 1:
print(userBottle , "bottle of pop on the wall, ", userBottle , "bottle of pop" ,
"\ntake one down, pass it around, " , "no bottles of pop on the wall")
input("\nThank you for playing! Press Enter to exit.")
因此,如果用戶輸入任何低於100的數字,程序將完美工作。但是,如果用戶輸入超過99的任何東西,那就是我遇到問題的地方。
會發生什麼是循環將運行到1,但不會結束。它會重複一次,它會返回:
1 bottles of pop on the wall, 1 bottles of pop
take one down, pass it around, 0 bottles of pop on the wall
0 bottle of pop on the wall, 0 bottle of pop
take one down, pass it around, no bottles of pop on the wall
Thank you for playing! Press Enter to exit.
顯然這是不正確的。我的循環出了什麼問題,所以我可以確保當用戶輸入大於99的數字時不會發生這種情況?
非常感謝,我非常感謝您的幫助!
當我還是個孩子的時候,這是瓶啤酒...... – 2014-10-12 04:06:50
如果count> 99並且userBottle變爲99,那麼newBottle是不是98? – csmckelvey 2014-10-12 04:08:36
首先,我將把n> 99的檢查移出循環。一旦你檢查過了,它再也不會是假的了。我相信這也能修復你的bug – 2014-10-12 04:09:27