2015-11-30 19 views
1

我需要能夠循環條件的代碼,如果用戶想重複該程序,那麼它必須循環。如果用戶想要退出該程序,則應該顯示所有超速汽車的車牌。這是我迄今爲止:速度傳感器程序,循環,python 3,A級

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) 

回答

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) 
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循環中使用了你的代碼。請查看while循環中的文檔以獲取更多信息,https://wiki.python.org/moin/WhileLoop