(Python)For循环语法 - 只执行一个项目?

时间:2012-08-07 10:35:26

标签: python list for-loop while-loop

对于python /编程而言,这是我最大的项目。

我正在编写一个程序,可以为你做SUVAT方程式。 (SUVAT方程用于找到具有恒定速度的物体的位移,开始/结束速度,加速度和行进时间,您可以将它们称为不同的东西。)

我做了这个清单:

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

用于以下while / 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."

希望我在代码中写的评论应该解释我的意图,如果没有,请随时提出任何问题。

问题在于,当我运行代码并输入choice1时,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 个答案:

答案 0 :(得分: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.e 'Displacement' != 'displacement'