如何从用户输入重置/重启Python程序?

时间:2014-02-13 03:07:13

标签: python

我想根据用户输入重置/重启我的程序。因此,如果用户键入“是”并单击“输入”,则程序将重置/重新启动并重新开始。我正在制作能量计算器;物理问题。输出是机械能,动能和势能。所有的公式都被正确编码,一切都按预期工作,除非我无法重新启动程序而不点击文件并重新打开。

#Importing "time" and "math" so I can use the time.sleep and rounding functions
import time
import math
restart=1
user_r1=float(input ("What is the mass of your object (kg) = "))
print ("")
user_r2=float(input ("Whats is the height you are dropping from (m) = "))
print ("")
user_r3=float(input ("What is the velocity (m/s) = "))
#Formulas that solve from the inputs given
EKinetic = 0.5 * user_r1 * user_r3 * user_r3
EPotential = user_r1 * 9.81 * user_r2
MechEnergy = (EPotential) + (EKinetic)
#Rounding - To change the ammount of sigdigs change the # infront of the f'
EKinetic='%.1f' % EKinetic
EPotential='%.1f' % EPotential
MechEnergy='%.1f' % MechEnergy
#Spitting out the info the user will see
print ("")
print ("===============================================================================")
print ("Kinetic Energy = ",EKinetic,"J")
print ("")
print ("Potential Energy = ",EPotential,"J")
print ("")
print ("Mechanical Energy = ",MechEnergy,"J")
print ("===============================================================================")
print ("")
#This time.sleep will make the program pause for (x# of seconds)
time.sleep(3)
user_r4=(input ("To do another calculation type yes and hit enter = "))
if user_r4 == ("yes"):
    print ("YAY")
    ###PUT RESTART CODE HERE###
    ###EVERYTHING DOWN ARE JUST PLACE HOLDERS FOR THE RESTART CODE###
else:
    print ("Please type yes to continue")
time.sleep(1)
user_r4=(input ("To do another calculation type yes and hit enter = "))
if user_r4 == ("yes"):
    print ("YAY")
    ###PUT RESTART CODE HERE###
else: print ("Thats enough!!!")
time.sleep(3)

1 个答案:

答案 0 :(得分:3)

您正在寻找的是一个简单的输入循环

while True:
    # Existing code here

    user_r4= input ("To do another calculation type yes and hit enter = ")

    # Exit the loop if the user does not want to proceed
    if len(user_r4) and user_r4[0] in "Yy":
        break