2012-08-07 89 views
0

对python /编程来说很新,这是我最大的项目。(Python)For循环语法 - 只执行一个项目?

我在写一个程序,可以为你做SUVAT方程。 (SUVAT公式用于查找排量,开始/结束的速度,加速度,并通过与等速对象旅行时,你可以打电话给他们不同的东西。)

我做了这个名单:

variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"] 

这是在下面的,而使用/ for循环:

a = 0 
while a==0: 
    for variable in variables: 

    # choice1 is what the user is looking to calculate 
    choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables)) 

    # will execute the following code when the for loop reaches an item that matches the raw_input 
    if choice1 == variable: 
     print "You chave chosen", choice1 
     variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on 
     a = 1 # Ends the for loop by making the while loop false 

    # This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen 
    else: 
     if choice1 == "Displacement": 
      pass 
     elif choice1 == "Start Velocity": 
      pass 
     elif choice1 == "End Velocity": 
      pass 
     elif choice1 == "Acceleration": 
      pass 

     # This error message will show if the input did not match any item in the list 
     else: 
      print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks." 

希望我已经写在代码中的注释应该解释我的意图,如果不是,随便问什么。

的问题是,当我运行的代码,输入选择1,for循环激活代码的最后一行:

else: 
    print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks." 

,然后提示我再次进入输入,并会做,因为很多次,因为它需要到我正在打字的列表上的项目。

但是,我特别编码,如果我输入的内容与列表上的项目不匹配for循环当前正在检查,但确实与列表中的其他项目匹配,那么它应该传递并循环检查下一个项目。

我可能在做一些愚蠢的事情,但我没有看到它,所以请帮我弄清楚我必须做些什么来获得我想要的结果?我认为这是我错了的语法,所以这就是为什么这是标题。

感谢您的任何帮助,我欣赏它。

+1

修复您的缩进 – 2012-08-07 10:36:46

回答

2

除了在你的粘贴代码的缩进问题,我将它改写为这样的:

while True: 
    choice = raw_input('...') 

    if choice in variables: 
     print "You chave chosen", choice 

     # Remove the chosen member from the list 
     variables = [v for v in variables if v != choice] 

     # Break out of loop 
     break 

    # Print error messages etc. 

还记得字符串比较是区分大小写的。 I。'Displacement' != 'displacement'

+0

抱歉,缩进的事情,这是一个粘贴错误,不是在程序上,但我已经修复它。 你说过的话会起作用我想,但我该如何让它从列表中删除所选的项目? – 2012-08-07 11:04:21

+0

@Ricochet_Bunny使用一种可能的解决方案更新答案以删除所选项目。 – 2012-08-07 11:07:06

+0

谢谢,这真的很棒,它的工作!如果你有时间,你会介意解释你添加的行吗?我还没有见过像以前那样使用过的东西。 – 2012-08-07 11:11:30