速度传感器程序,循环,python 3,A级

时间:2015-11-30 10:19:55

标签: python loops python-3.x

我需要能够在条件下循环此代码,如果用户想要重复该程序,那么它必须循环。如果用户想要退出程序,则应显示超速车的所有车牌。这就是我到目前为止所做的:

import time
capturedtime=time.time()

speed_limit = 30
distance = 50

numberplates = []
newplate = ("Input number plate")

input("Press enter to start")
start_time = time.time()
input("Press enter to stop")
stop_time = time.time()
capturedtime = stop_time - start_time

print('Time taken: {:.2f} seconds'.format(capturedtime))
print('Distance: {:.2f}'.format(distance))
speed = distance / capturedtime
print('Speed: {:.2f}'.format(speed))

if speed > speed_limit:
    print("You were breaking the speed limit")
    numberplates.append(newplate)

2 个答案:

答案 0 :(得分:0)

我不确定这是否是您正在寻找的,但请尝试以下方法。

import time
capturedtime = time.time()

speed_limit = 30
distance = 500

numberplates = []

loops = True

while(loops):
    try:
        newplate = input("Input number plate: ")

        input("Press enter to start: ")
        start_time = time.time()
        input("Press enter to stop: ")
        stop_time = time.time()
        capturedtime = stop_time - start_time

        print('Time taken: {:.2f} seconds'.format(capturedtime))
        print('Distance: {:.2f}'.format(distance))
        speed = distance / capturedtime
        print('Speed: {:.2f}'.format(speed))

        if speed > speed_limit:
            print("You were breaking the speed limit")
            numberplates.append(newplate)

        exit = input("Press x to exit, Press enter to continue: ")
        if exit.lower() == 'x':
            loops = False
    except Exception:
        pass

print(numberplates)

我刚刚在循环中使用了你的代码。有关详细信息,请查看while循环文档,https://wiki.python.org/moin/WhileLoop

答案 1 :(得分:0)

如果我理解正确,您可以将所有代码放入while循环并通过另一个输入()停止。

示例:

import time
exit = True
'''your variables'''
while(exit):
    '''your Code'''
    x = input("Enter 'y' if you want to exit.")
    if x.lower() == y:
        exit = False
        print("All speeding Cars:") # Print all the Cars!
        for plate in numberplates:
            print(plate)