速度传感器程序,循环,python3,A

2024-10-04 05:31:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要能够循环这个代码的条件,如果用户想重复的程序,那么它必须循环。如果用户希望退出程序,则应显示所有超速行驶的车牌号。到目前为止,我得到的是:

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)

Tags: 用户程序formatinputtimestartdistancepress
2条回答

如果我理解正确,您可以将所有代码放入while循环中,然后通过另一个input()停止它。在

示例:

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)

我不太确定这是否是你要找的,但试试下面的方法。在

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循环中使用了你的代码。有关详细信息,请查看while循环的文档,https://wiki.python.org/moin/WhileLoop

相关问题 更多 >