2014-03-05 61 views
0

我试过几件事情来解决这个循环,它只是不会工作。至于现在它给了我一个语法错误,突出显示第一个打印语句中的yes后面的引号......我没有看到任何错误吗?时髦虽然循环/时髦的语法错误Python 2.7

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 
+0

很明显,它也复制了滑稽....变量在我的评论结束... – Carsomyr

+1

您的代码适合我。 – Hoppo

+0

什么是给你一个语法错误 - 在你的编辑器中突出显示,或者当你尝试运行时解释器?...你使用的是什么版本的Python:是2.x还是3.x? –

回答

1

编辑:你的问题的解决方案是由森美阿鲁斯给出的 - 我提出的观点仅仅是良好的Python的做法。

打印出他们与各种类型的字符串(在你的情况,字符串,然后INT,其次是字符串中的首选,Python的方式,是使用上的字符串操作.format(*args)功能。在这种情况下,你可以使用

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

如果你要打印出多个参数,第一个是由{0}引用,接下来通过“{1}”,等等。

虽然它也适用于使用C-esque %运营商格式化蜇(例如You have answered yes %d times " % Ycount,这我不是首选。

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

+0

虽然这是有用的信息 - 它没有解决OP所假设的错误......(很可能他们使用的是3.x版本,并且需要使用“print”作为函数,而不是声明。 ..) –

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