将for循环集成到if语句中

时间:2012-08-06 22:38:54

标签: python for-loop

这是一个双重问题,但它让我感到困惑。我目前有以下代码:

from __future__ import division
import math

function = int(raw_input("Type function no.: "))


if function == 1:
    a = float(raw_input ("Enter average speed: "))
    b = float(raw_input ("Enter length of path: "))
    answer= float(b)/a
    print "Answer=", float(answer),

elif function == 2:
    mass_kg = int(input("What is your mass in kilograms?" ))
    mass_stone = mass_kg * 2.2 / 14
    print "You weigh", mass_stone, "stone."

else: print "Please enter a function number."

现在,我想要一些循环(我猜它是一个for循环,但我不完全确定)所以在一个函数完成后,它会返回到顶部,因此,用户可以输入新的功能编号并执行不同的等式。我该怎么做?我一直试图想办法过去半小时,但没有任何结果。

尽量忽略代码中的任何混乱......需要进行一些清理。

3 个答案:

答案 0 :(得分:6)

最好使用while - 循环来控制重复,而不是for - 循环。这样,用户不限于固定数量的重复,只要他们想要,他们就可以继续。要退出,用户输入值

from __future__ import division
import math

function = int(raw_input("Type function no.: "))

while function > 0:
    if function == 1:
        a = float(raw_input ("Enter average speed: "))
        b = float(raw_input ("Enter length of path: "))
        answer = b/a
        print "Answer=", float(answer),
    elif function == 2:
        mass_kg = int(input("What is your mass in kilograms?" ))
        mass_stone = mass_kg * 2.2 / 14
        print "You weigh", mass_stone, "stone."

    print 'Enter a value <= 0 for function number to quit.'
    function = int(raw_input("Type function no.: "))

您可以根据需要调整此项(例如,终止条件)。例如,您可以指定0是唯一的终止值等。

替代 是一个“永远”运行的循环,如果提供了特定的功能编号,则会中断(在此示例中为0)。这是这种方法的骨架/草图:

    function = int(raw_input("Type function no.: "))

    while True:
       if function == 1:
          ...
       elif function == 2:
          ...
       elif function == 0:
          break      # terminate the loop.

      print 'Enter 0 for function number to quit.'
      function = int(raw_input("Type function no.: "))

注意:如果您迭代已知/固定次数,则for - 循环是最合适的,例如在序列上(如列表),或者如果你想以某种方式限制重复。为了给您的用户更多的灵活性,while - 循环是一种更好的方法。

答案 1 :(得分:2)

您只需将整个脚本包装在循环中,例如:

from __future__ import division
import math

for _ in range(10):

    function = int(raw_input("Type function no.: "))


    if function == 1:
        a = float(raw_input ("Enter average speed: "))
        b = float(raw_input ("Enter length of path: "))
        answer= float(b)/a
        print "Answer=", float(answer),

    elif function == 2:
        mass_kg = int(input("What is your mass in kilograms?" ))
        mass_stone = mass_kg * 2.2 / 14
        print "You weigh", mass_stone, "stone."

    else: print "Please enter a function number."

这将连续10次运行你的if语句。

答案 2 :(得分:2)

我试试这个:

while True:
    function = ...
    if function == 0:
        break
    elif ...