【问题标题】:Why isn't my if statement executing its print statement Python 2.7.11为什么我的 if 语句不执行其打印语句 Python 2.7.11
【发布时间】:2016-04-24 06:47:37
【问题描述】:

我在 Python 2.7.11 中有一个 main 方法(在第一次执行后)会询问用户是否要继续 (y/n)'y' 的响应重新执行了我在main 中实例化的 while 循环就好了,并且考虑了错误的输入并重新提出了问题。但是,当用户输入'n' 时,它不会打印'Goodbye.',而是在没有到达print 语句的情况下退出循环。这是我的代码:

def main():

    will_continue = 'y' # Default for the first execution

    while will_continue == 'y':
        # A bunch of execution code here for the program...

        # After executing rest of code
        will_continue = raw_input('Do you wish to continue? (y/n): ')

        while will_continue != 'y' and will_continue != 'n':
            if will_continue == 'n':
                print 'Goodbye.'
            else:
                will_continue = raw_input('Invalid input. Do you wish to continue? (y/n): ')


if __name__ == "__main__":
    main()

我想我的问题可能是while continue != 'y' and continue != 'n': 中的and,所以我将其更改为while continue != 'y' or continue != 'n':,但这会让我陷入'Goodbye' 的无限循环,如果我输入'n' 或无限无响应如果我输入'y'

关于为什么 print 'Goodbye.' 语句在终止 main 之前不会执行的任何想法?

【问题讨论】:

  • 你在哪里定义 var will_continue
  • continue 是 python 保留关键字。您不能将其用作 var 名称。
  • @WreckeR 你确定吗?我似乎记得我有时会在不知不觉中覆盖保留的关键字。
  • Python 2.7 不允许我执行以continue 作为变量名的脚本。它可能的旧版本 python 允许您使用保留关键字。
  • 好的。我把它修回原来的样子。

标签: python python-2.7 if-statement printing while-loop


【解决方案1】:

您要求用户在 else 块中输入。如果用户输入'n',while 块将在下一次迭代中终止,导致您的if will_continue == 'n' 永远不会执行。一个快速的解决方法是将您的 if 块放在内部 while 循环的外部

或者,您可以避开 if 块,并简单地让程序在末尾打印“再见”,无论发生什么。

【讨论】:

  • 啊!做到了!非常感谢,这是我的逻辑错误。
【解决方案2】:

will_continue 在您上面的代码中永远不会改变,所以它永远不会是'n'。

【讨论】:

  • 每次在while循环结束时都会改变,因为continue被重新定义为新的raw_input
  • @Jodo1992 实际上,它不是。你正在改变continue,而不是will_continue
  • 我编辑了代码。 will_continue 现在是 continue 以节省空间。
  • @Jodo1992 你错过了一个,这给你的问题带来了新的问题。
【解决方案3】:

这是您的代码的更新版本。

def main():

    con = 'y' # Default for the first execution

    while con == 'y':
        # A bunch of execution code here for the program...

        # After executing rest of code
        con = raw_input('Do you wish to continue? (y/n): ')
        while con != 'y' and con != 'n':
            con = raw_input('Invalid Input. Type y/n: ')
        if con == 'n':
            print 'Goodbye.'


if __name__ == "__main__":
    main()

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多