Python - "While" 循环卡住了

Python - "While" loop is stuck

我创建的 While 循环不会退出。我已经测试了很多次,但无法弄清楚为什么。如果我输入“0764526413”的 ISBN 代码,它 returns "All Numbers" 并退出循环。但是如果我用代码中的一个字母测试它(确保它循环回来),它会回到顶部并要求我再次输入代码。我这样做了,然后我输入了全数字代码。此时,我处于无限循环中。即使第二次输入全数字代码也不会退出。我不明白为什么如果我在第一次输入全数字代码时它似乎在正确循环,但如果我输入不正确的代码然后输入正确的代码则不会。

代码如下:

# 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'

我知道有些代码可能看起来很奇怪,但这实际上是我正在为家庭作业编写的更大程序的一小部分。这是唯一给我带来问题的部分。任何帮助是极大的赞赏。我真的希望它是我没有看到的小东西,因为我已经为整个程序工作了好几天。非常感谢大家!请知道我需要这个 return 或者 "All Numbers" 并在正确输入 ISBN 时退出循环,或者在输入数字以外的任何内容时返回循环。

您应该在以下时间之前将 ISBN_temp 重新设置为空字符串:

for num in ISBN_no_check:
    ISBN_temp = ISBN_temp + str(num)

否则你每次迭代都会继续添加到同一个字符串。

ISBN_temp 在 while 循环的迭代之间保留。没有明确的理由将其保留在 while 循环之外

此循环的替代方法

for num in ISBN_no_check:
    ISBN_temp = ISBN_temp + str(num)

是将数字

生成新的字符串
ISBN_temp = ''.join(str(num) for num in ISBN_no_check)

当数字检查通过时,您还可以使用 while Truebreak。那么你不需要 digits 变量