当输入与while循环编号相同时,如何使while循环继续

时间:2018-03-15 18:11:38

标签: python

我正在制作一个物理二维运动计算器,它要求用户输入并将该值添加到python中的变量中。我遇到的问题是我使用的while循环有,而V == 0:如果用户输入0,程序会不断要求V的新值。我该怎么做才能让程序使用如果值为0则输入值,并停止程序再次询问。这是我的代码。

  while V == 0:
    V = float(input("What is the final velocity?"))
    if V == 0:
      pass

以下是我想要使用的等式

    v = V - a*t

如果用户输入0,我想使用数字0,但目前它只是继续前进,我不想要这个。

v = 0
V = 0
d = 0
D = 0
t = 0
a = 0

if inp2 == "2": #solve for final velocity here
  print("We will solve for final velocity")
  while v == 0:
    v = float(input("What is the initial velocity?"))
  while a == 0:
    a = float(input("What is the acceleration?"))
    if a == 0:
      pass
  while t == 0:
    t = float(input("What is the total time"))
  V = v + a*t
  print ("The final velocity is"), V

1 个答案:

答案 0 :(得分:1)

如果您不关心验证响应,可以删除while循环。如果你想验证一些响应(确保它们是数字而不是零),最好这样做。

def input_float(s, zero_allowed=False):
    while True:
        try:
            ans = float(input(s))
            if ans == 0 and not zero_allowed:
                print("Please enter a non-zero number")
            else:
                return ans
        except ValueError: # in case the user enters text
            print("Please enter a number")


if inp2 == "2": #solve for final velocity here
    print("We will solve for final velocity")
    v = input_float("What is the initial velocity?", zero_allowed=True)
    a = input_float("What is the acceleration?")
    t = input_float("What is the total time?")
    V = v + a * t
    print("The final velocity is", V)

这消除了将值启动为零的需要。