Attribute error when generating random numbers in Python

Question:

I asked a similar question regarding this same piece of code earlier but once again I have found myself stuck. Particularly on the generation of a license plate containing two letters, two numbers, and then two letters. I hope that this question isn’t a duplicate but in this circumstance I am very stuck with what to do, this is the code so far and I hope you can identify where I am going wrong:

from datetime import date, datetime, time, timedelta
import time, string
from random import uniform, random

def timeDelta():
    print("Average Speed Checker")
    start = (input("Car has passed Cam1: "))
    licensePlate = str(firstLetters + randomNumber + " " + secondLetters)
    print(licensePlate)
    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 = 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 travelling in MPH at: {0}".format(speedCarMph))
        if speedCarMph > 60:
            fileInput:

def possibleNumber():
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0)
    randomNumber = random.sample(possibleNumbers, 2)

def randomLetters1(y):
    return ''.join(random.choice(string.ascii_uppercase) for x in             range(y))
firstLetters = (randomLetters1(2))
secondLetters = (randomLetters1(3))

print("Choose which function you want to use: ")
while True:
    answer = (input("Choice: "))
    if answer in ("speed"):
        timeDelta()
else:
    print("Invalid response")

According to python, the issue is to do with this:

AttributeError: 'builtin_function_or_method' object has no attribute 'choice'
Asked By: TooLateTheHero

||

Answers:

You did not import the random module. You imported the random.random() function:

from random import uniform, random

If you wanted to use choice() and sample() as well, import that in addition:

from random import uniform, random, choice, sample

and adjust your use of those functions:

def possibleNumber():
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0)
    randomNumber = sample(possibleNumbers, 2)

def randomLetters1(y):
    return ''.join(choice(string.ascii_uppercase) for x in range(y))

Or, instead, import just the module:

import random

and your code will work as you don’t actually use random() anywhere, provided you replace uniform() with random.uniform():

camInput2 = camInput1 + timedelta(seconds = random.uniform(5, 10))

I’ll reiterate again that you don’t need to create camInput2, as camInput1 + some_timedelta - camInput1 produces the same value as some_timedelta; you can just use:

timeDelta = timedelta(seconds = random.uniform(5, 10))

You never call the randomNumbers() function, nor does the function return anything. The randomNumber local name in that function is not available outside of the function.

Have the function return the result and use the function where you now try to use the result via the randomNumber name:

def possibleNumber():
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0)
    return random.sample(possibleNumbers, 2)

and

licensePlate = str(firstLetters + possibleNumber() + " " + secondLetters)
Answered By: Martijn Pieters

random.random, which you refer to in your code as simply random, because you imported it directly into your namespace (from random import ... random) instead of importing the entire module (import random), is a free function, which does not have an attribute named choice.

For the code you’ve written, calling random.choice, and random.sample, your import statement should be import random. Alternatively, switch your function calls to simply choice(...) and sample(...)

Answered By: twalberg

I encountered the same issue when one day my code stopped working because of this same error.
Reading the other answers i came up with this workaround:
Give an alias to the random module, so that when you call the alias.choice method there is no ambiguity:

import json,random as rd, string
from random import uniform, random, choice, sample

def randomString(stringLength):
    letters = string.ascii_letters
    return ''.join(rd.choice(letters) for i in range(stringLength))
Answered By: Kabir Lovero
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.