【问题标题】:Funky While loop / Funky syntax error Python 2.7 [closed]时髦的 While 循环/时髦的语法错误 Python 2.7 [关闭]
【发布时间】:2014-03-05 15:46:06
【问题描述】:

我尝试了几种方法来修复此循环,但它无法正常工作。截至目前,它给了我一个语法错误,在第一个打印语句中的 yes 之后突出显示引号......我看不出有什么问题吗?

Ycount = 0
Ncount = 0
Valid = ["Y","y"]
InValid = ["N","n"]
Quit = ["Q","q"]
Uinp = ""

while Uinp != "Q":
    Uinp = raw_input("Did you answer Y or N to the question(enter Q to quit)? ")
    if Uinp in Valid:
        Ycount = Ycount + 1
        print "You have answered yes" ,Ycount, "times"
        print "You have answered no" ,Ncount, "times"
    elif Uinp in InValid:
        Ncount = Ncount + 1
        print "You have answered yes" ,Ycount, "times"
        print "You have answered no" ,Ncount, "times"
    elif Uinp in Quit:
        break

【问题讨论】:

  • 显然它也很有趣地复制了......变量在我评论的末尾......
  • 你的代码适合我。
  • 什么是语法错误 - 编辑器中的突出显示,或者当您尝试运行它时的解释器?...您使用的是什么版本的 Python:它是 2.x 还是3.x ?
  • 我在该代码中根本看不到语法错误。如果这是 Python 3.x,您只会收到语法错误。使用 2to3 将其转换为 Python 3 兼容代码。
  • 我会推荐你​​关注Python naming conventions

标签: python syntax while-loop


【解决方案1】:

我已经在 python 2 下运行了您的代码,它按预期运行。

然而,在 python3 下,您需要进行一些更改才能运行它:

print "something"不再支持,需要使用 print ("something")

并且raw_input 被重命名为input

Ycount = 0
Ncount = 0
Valid = ["Y","y"]
InValid = ["N","n"]
Quit = ["Q","q"]
Uinp = ""

while Uinp != "Q":
    Uinp = input("Did you answer Y or N to the question(enter Q to quit)? ")
    if Uinp in Valid:
        Ycount = Ycount + 1
        print ("You have answered yes" ,Ycount, "times")
        print ("You have answered no" ,Ncount, "times")
    elif Uinp in InValid:
        Ncount = Ncount + 1
        print ("You have answered yes" ,Ycount, "times")
        print ("You have answered no" ,Ncount, "times")
    elif Uinp in Quit:
        break

【讨论】:

    【解决方案2】:

    编辑:Sammy Arous 给出了您的问题的解决方案——我要说的只是良好的 Python 实践。

    打印出具有各种类型的字符串的首选 Pythonic 方法(在您的情况下,字符串,后跟 int,然后是字符串,是使用对字符串进行操作的 .format(*args) 函数。在这种情况下,您可以用

    print ("You have answered yes {0} times".format(Ycount))
    

    如果要打印多个参数,第一个由{0} 引用,下一个由'{1}' 引用,依此类推。

    虽然使用 C 风格的 % 运算符来格式化字符串也是有效的(例如 You have answered yes %d times " % Ycount,但这不是首选。

    尝试使用大括号语法。在大型项目中,它会显着提高您的代码速度(计算并打印一个字符串,而不是打印三个字符串),并且通常更符合 Python 的习惯。

    【讨论】:

    • 虽然这是有用的信息 - 它并没有解决 OP 的假设错误......(很可能他们使用的是 3.x 版本并且需要使用 print 作为函数,不是声明...)
    猜你喜欢
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多