【问题标题】:Python - "While" loop is stuckPython - “当”循环被卡住
【发布时间】:2018-05-16 16:55:03
【问题描述】:

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

代码如下:

# 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_temptemp_ISBN 用于表示不同的东西。这很令人困惑。 withoutCheckDigitoriginalUserInput 分别如何?
  • @GrzegorzOledzki - 谢谢!!!!!!我知道这都是大写……我的意思是每一点。它不会让我在这一点上接受你的答案(你在下面做的那个),但它奏效了!我的意思是,它当然有效,但我很兴奋。一看到你的回复,就觉得很有道理。非常感谢你。感谢您在上面的建议,当我想出变量名称时,我已经累了,只是想让代码正常工作。
  • @cricket_007 - 谢谢你的信息。我是 Python 新手(我在编程的第一学期),对 Stack Overflow 来说真的很陌生。这已成为我最喜欢的网站。这里的每个人都非常乐于助人。

标签: python loops while-loop infinite


【解决方案1】:

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

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

否则,您会在每次迭代中继续添加相同的字符串。

【讨论】:

  • 谢谢格热戈兹!我知道这一定是我忽略的一些简单的事情。
【解决方案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 Truebreak。那你就不需要digits变量了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    相关资源
    最近更新 更多