Python 当输入与while循环编号相同时,如何使while循环继续
我正在制作一个物理2d运动计算器,它要求用户输入并将该值添加到python中的变量中。我遇到的问题是,我使用的while循环有while V==0:如果用户输入0,程序会不断要求V的新值。如果值为0,我该怎么做才能使程序使用输入的值,并阻止程序再次询问。这是我的密码Python 当输入与while循环编号相同时,如何使while循环继续,python,Python,我正在制作一个物理2d运动计算器,它要求用户输入并将该值添加到python中的变量中。我遇到的问题是,我使用的while循环有while V==0:如果用户输入0,程序会不断要求V的新值。如果值为0,我该怎么做才能使程序使用输入的值,并阻止程序再次询问。这是我的密码 while V == 0: V = float(input("What is the final velocity?")) if V == 0: pass 这是我想用的方程式 v = V -
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
如果您不关心验证响应,则可以删除
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)
这就不需要将值初始化为零。如果您不希望程序在
V==0
时循环,那么为什么这是您的while条件?最初,我给每个变量0赋值,这样while循环将运行。在程序开始时,我总是将变量中的所有值重新赋值为0,以便while循环运行。有更好的方法吗?变量最初都被指定为0作为它们的值,以便在while循环中运行它们,但是如果用户输入0,我希望程序将其保存为变量的值,并继续程序的下一部分@davym显示更多的代码,以便更容易理解您要完成的任务。如果希望0是一个可接受的值,则首先将变量设置为其他值,例如None
,并将其用作条件。