Reputation: 55
Basically, I'm trying to make a program that will calculate the average speed between two points that are 200m apart, and of course convert that into mph so I can say whether it is above or below the speed limit. I'm having problems making it so that it adds random numbers to the value of datetime.now() as it is telling me "NameError: name 'random' is not defined". There's probably an incredibly simple solution to this, I'm just very unsure of how to use the random in this instance. I'm not really sure how to go about fixing this, thanks for any help. Here is my code so far:
from datetime import date, datetime, time, timedelta
from random import seed, randrange, uniform
import time
def timeDelta():
print("Average Speed Checker")
start = (input("Car has passed Cam1: "))
if start in ("y"):
camInput1 = datetime.now()
print(camInput1)
print("Car is travelling...")
time.sleep(1)
print("Car is travelling...")
time.sleep(1)
print("Car has passed cam2")
camInput2 = camInput1 + timedelta(seconds = random.uniform(5, 10))
timeDelta = camInput2 - camInput1
distance = 200
duration = timeDelta.total_seconds()
print("Time Delta is equal to: {0}".format(duration))
speedCarMs = distance/duration
print("Car is travelling in m/s at: {0}".format(speedCarMs))
speedCarMph = 2.237*speedCarMs
print("Car is traveelling in MPH at: {0}".format(speedCarMph))
print("Choose which function you want to use: ")
while True:
choice = (input("Choice: "))
if choice in ("speed"):
timeDelta()
else:
print("Invalid response")
Upvotes: 0
Views: 1095
Reputation: 1122012
You imported the name uniform
(among others), not the name random
:
from random import seed, randrange, uniform
This adds seed
, randrange
and uniform
to your globals.
Simple remove the random.
prefix and use the uniform
global directly:
camInput2 = camInput1 + timedelta(seconds = uniform(5, 10))
Note that you can simplify your code here; there is no need to add to camInput1
then subtract that again. Just use:
timeDelta = timedelta(seconds = uniform(5, 10))
datetime_value + timedelta_value - datetime_value
produces just timedelta_value
again.
Upvotes: 2
Reputation:
Because you imported like this:
from random import seed, randrange, uniform
you don't need to reference the namespace. Instead of this:
timedelta(seconds = random.uniform(5, 10))
Try:
timedelta(seconds=uniform(5, 10))
This is because when you import like from ... import ...
, it adds them to the current scope. Just like how a = 29
would add the variable a
to the scope with value 29
, from random import uniform
would add uniform
to the scope as a function.
Upvotes: 2