Funky While循环/ Funky语法错误Python 2.7

时间:2014-03-05 15:46:07

标签: python syntax while-loop

我已经尝试了几个方法来修复这个循环,它只是不会工作。截至目前,它给我一个语法错误,在第一个打印语句中的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

2 个答案:

答案 0 :(得分:1)

编辑:问题的解决方案由Sammy Arous提供 - 我的观点是优秀的Python练习。

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

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

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

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

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

答案 1 :(得分: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