2017-12-02 361 views
0

我创建的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时退出循环,或者如果输入除数字之外的任何内容,则循环返回。

+0

@MartijnPieters - 谢谢你指出。我实际上已经在我的代码中正确缩进了所有内容,但是在我粘贴了所有内容后,我忘了在这里更多地选择标签。我修复了缩进。 – Rogue

+1

@盗贼:不要手工缩进所有东西。粘贴您的代码,在编辑器中选择所有这些代码行,然后使用工具栏上的“{}”按钮添加缩进。 –

+1

另一个建议是想想更好的变量名称。 'ISBN_temp'和'temp_ISBN'用来表示不同的意思。这很混乱。如何分别使用'withoutCheckDigit'和'originalUserInput'? –

回答

3

您应该重新设定ISBN_temp空字符串之前:

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

否则你继续增加非常相同的字符串,每次迭代。

+0

谢谢Grzegorz!我知道它必须是我忽略的简单东西。 – Rogue

2

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 True当数字检查通过时与break。那么你不需要digits变量