【问题标题】:(Python) For loop syntax - execute for only one item?(Python) For 循环语法 - 只执行一项?
【发布时间】:2012-08-04 08:33:05
【问题描述】:

一般来说,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."

希望我在代码中编写的 cmets 能够解释我的意图,如果没有,请随时提出任何问题。

问题是当我运行代码并输入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 循环当前正在检查的列表中的项目不匹配,但与列表中的其他项目之一匹配,那么它应该通过并循环循环以检查下一项。

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

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

【问题讨论】:

    标签: python list for-loop while-loop


    【解决方案1】:

    除了粘贴代码中的缩进问题之外,我会这样重写它:

    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'

    【讨论】:

    • 对不起,缩进的事情,这是一个粘贴错误,不在程序上,但我已经修复了它。我认为你所说的会起作用,但我将如何使它从列表中删除所选项目?
    • @Ricochet_Bunny 用一种可能的解决方案更新了答案以删除所选项目。
    • 谢谢,它真的很好用!如果你有时间,你介意解释一下你添加的那行吗?我以前没见过这样的东西。
    • @Ricochet_Bunny 它叫list comprehension
    • 谢谢你是一个真正的帮助我很感激。
    猜你喜欢
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2021-06-15
    相关资源
    最近更新 更多