我創建的While循環不會退出。我已經多次測試過,無法找出原因。如果輸入ISBN編碼「0764526413」,則返回「所有編號」並退出循環。但是如果我用代碼中的一個字母測試它(確保它循環回去),它會回到頂部並要求我再次輸入代碼。我這樣做,然後輸入所有數字代碼。在這一點上,我陷入了無限循環。即使第二次輸入全部數字代碼,它也不會退出。我不明白爲什麼它似乎循環正確,如果我第一次全面輸入所有的數字代碼,但如果我輸入不正確的代碼,然後輸入正確的代碼,則不會。Python - 「While」循環卡住
代碼如下:
# Variable to start loop
Digits = 'N'
ISBN_temp = ''
# The loop asks for the ISBN, removes the dashes, removes check digit,
# And checks to see if the info entered is numeric or not.
while Digits == 'N':
print('Please enter the ISBN code with or without the check digit.')
temp_ISBN = input('You may enter it with dashes if you like: ')
ISBN_no_dash = temp_ISBN.replace('-','')
no_dash_list = list(ISBN_no_dash)
# If the user entered a check digit, remove it.
if len(no_dash_list) == 10:
del no_dash_list[9]
ISBN_no_check = no_dash_list
elif len(no_dash_list) == 13:
del no_dash_list[12]
ISBN_no_check = no_dash_list
else:
ISBN_no_check = no_dash_list
# Turn list back into a string and then make sure all characters are
# Numeric.
for num in ISBN_no_check:
ISBN_temp = ISBN_temp + str(num)
if ISBN_temp.isnumeric():
print('All numbers')
Digits = 'Y'
else:
print()
print('Please verify and reenter the ISBN number.')
print()
Digits = 'N'
我知道的一些編碼看起來不可思議,但其實這是一個更大的計劃,我寫家庭作業的一小部分。這是給我問題的唯一部分。任何幫助是極大的讚賞。我真的很希望這是一件小事,我只是沒有看到,因爲我一直在整個項目上工作數天。非常感謝大家!請知道,我需要這個或者返回「所有數字」,並在正確輸入ISBN時退出循環,或者如果輸入除數字之外的任何內容,則循環返回。
@MartijnPieters - 謝謝你指出。我實際上已經在我的代碼中正確縮進了所有內容,但是在我粘貼了所有內容後,我忘了在這裏更多地選擇標籤。我修復了縮進。 – Rogue
@盜賊:不要手工縮進所有東西。粘貼您的代碼,在編輯器中選擇所有這些代碼行,然後使用工具欄上的「{}」按鈕添加縮進。 –
另一個建議是想想更好的變量名稱。 'ISBN_temp'和'temp_ISBN'用來表示不同的意思。這很混亂。如何分別使用'withoutCheckDigit'和'originalUserInput'? –