-7
from datetime import datetime

time_enter = datetime.now()
print ("Has a car entered the section?")
if raw_input() == "yes":
    print (datetime.now().strftime("%H:%M:%S.%f"))
    datetime.now().strftime("%H:%M:%S.%f")
    time_leave= datetime.now()
    print ("Has a car leaved the section?")
    if raw_input() == "yes":
        print (datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        time_taken_to_travel = time_leave - time_enter
        print (time_taken_to_travel)
    else:
        print ("No car has leaved!")

else:
    print ("No car has entered!")
    print ("No car has leaved!")

Hello, I have edited my code as said below, but it says that there is some kind of an error with the line 5, and the raw input. Can you help to correct it?

Has a car entered the section?
Traceback (most recent call last):
  File "E:\code.py", line 5, in <module>
    if raw_input() == "yes":
NameError: name 'raw_input' is not defined

1 Answers1

0

Without being too harsh, I must say your code looks like one big spaghetti mess. New lines, separating logic into functions and so on would easily give a better overview of the code.

On initial sight, this part of the code is at least wrong. When you define an else statement, it needs to have an indented block to execute.

 else:
 print("No car has leaved!")
 time_taken_to_travel = time_leave - time_enter
 print (time_taken_to_travel)

Should be something similar to this, or what you are trying to do :)

 else:
     print("No car has leaved!")

 time_taken_to_travel = time_leave - time_enter
 print (time_taken_to_travel)

EDIT:

OK, off the top, fixed the code to run in Python 2.7, take care of the different use of print if you run in Python > 3.

First off, when writing Python, the indentation is super important. Distinguish between 4 spaces and indentations. Your code was indented a space too much. You do not need to call datetime.datetime.now, just datetime.now. Secondly, why convert the dates to string when you subtract em? Keep them as dates and for input, intput is not the best solution. It will validate the inputted string. Use raw_input instead.

from datetime import datetime

time_enter = datetime.now()
print "Has a car entered the section?"
if raw_input() == "yes":
    print datetime.now().strftime("%H:%M:%S.%f")
    datetime.now().strftime("%H:%M:%S.%f")
    time_leave= datetime.now()
    print "Has a car leaved the section?"
    if raw_input() == "yes":
        print datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    else:
        print "No car has leaved!"
        time_taken_to_travel = time_leave - time_enter
        print time_taken_to_travel
else:
    print "No car has entered!"
    print "No car has leaved!"

With the output:

Has a car entered the section?
yes
11:41:54.281000
Has a car leaved the section?
yes
2015-10-15 11:41:55
Karel Vlk
  • 230
  • 1
  • 6
mrhn
  • 17,961
  • 4
  • 27
  • 46