无限循环Python

时间:2016-07-14 16:12:28

标签: python

一个小小的背景故事:我必须在Python中创建一个代码,帮助用户对学校项目的手机进行故障排除。用户只能对程序提出的问题回答“是”或“否”。

我遇到的问题是输入“是”或“否”以外的其他内容会使while循环无限循环,而不是仅显示一次并在用户输入“是”后转到下一个问题或'否'。

代码尚未完成,这就是为什么它可能看起来像缺少一些建议/问题。

编辑:代码现在正常运行!谢谢你的回答,伙计们!他们真的很有帮助!

 <CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox"
    android:buttonTint="@color/lightColoral"
    />

3 个答案:

答案 0 :(得分:2)

while phoneFault != "Yes" and phoneFault != "No":
    print("Error; you can only answer 'Yes' or 'No' to the questions.")

这条线是罪魁祸首。只要有人输入"Yes""No"以外的内容,我们就会输入此while循环。在此while循环期间,phoneFault的值保持不变,因此我们将继续无限地打印错误消息。

如果您在此while循环期间添加了更改phoneFault值的功能,则可以解决您的问题。

答案 1 :(得分:0)

每当你得到一个无限循环,看看条件,然后看看可能会改变那个条件。你可能想要这样的东西,把raw_input放在循环中:

phoneFault = None
while phoneFault != "Yes" and phoneFault != "No":
    phoneFault = raw_input("Is your phone physically damaged?")
    print("Error; you can only answer 'Yes' or 'No' to the questions.")

但这不是非常用户友好。必须按&lt;转移&gt;得到大写的Y或N.你可以考虑这个:

phoneFault = None
while phoneFault != "yes" and phoneFault != "no":
    phoneFault = raw_input("Is your phone physically damaged (Yes/No)? ").lower()

答案 2 :(得分:0)

虽然每if条件只有两个答案,但我个人更喜欢if phoneFault in ('Yes','yes'):会员资格测试。这使代码更具可读性。如果您希望phoneFault匹配类似“是”或“否”的任何内容,您可能会对re模块中的正则表达式感兴趣。

相关问题