【问题标题】:Python raw_input with while isn't working properlyPython raw_input with while 无法正常工作
【发布时间】:2014-10-16 10:32:19
【问题描述】:

我正在尝试使用 raw_input() 从用户那里获取字符输入,看看这是 Y 还是 N。应该完成这项工作的代码如下:

#
# Things I have done before
#
c = ""
while c.capitalize() != "Y" or c.capitalize() != "N":
    c = raw_input("\n\n If you wish to continue, press Y (or N to terminate) ")

if c.capitalize() == "N":
    system.exit("Stopped script......check your files if necessary\n\n");
else:
    #Other things to do

目前,即使按Y或N,我也会反复收到提示。不知道这是什么问题。我尝试使用 input() 而不是 raw_input() 但我认为我使用的是旧版本的 python (2x),这就是为什么需要使用 raw_input。

感谢任何帮助。

【问题讨论】:

标签: python input while-loop


【解决方案1】:

你的逻辑有问题:

while c.capitalize() != "Y" or c.capitalize() != "N":

如果我输入“Y”,第一项是False,但第二项是TrueFalse or TrueTrue,while 块被执行。如果我输入“N”,同样的事情。你必须使用and:

while c.capitalize() != "Y" and c.capitalize() != "N":

【讨论】:

  • 你很好......真的很漂亮!
【解决方案2】:

你的条件不对:
如果c=='N',那么第一部分(c!=Y)为真,所以你会循环(反之,如果c=='Y',c不等于'N')

改成

while (c.capitalize() != "Y" and c.capitalize() != "N"):

或更好:

while (c.capitalize() not in ['Y','N']):

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多