0

一般来说,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 循环当前正在检查的列表中的项目不匹配,但与列表中的其他项目之一匹配,那么它应该通过并循环检查下一个项目。

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

感谢您的帮助,我很感激。

4

1 回答 1

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.

还要记住,字符串比较区分大小写。即'Displacement' != 'displacement'

于 2012-08-07T10:46:10.437 回答