Python ошибка random

Всем привет. Недавно настроил среду Sublime, чтобы можно было запускать код через SublimeREPL. При запуске простейшего кода выдается ошибка с библиотекой рандома. Глянул свою версию, она 3.8.3. Проверил, установлен ли сам модуль, попробовал запустить через консоль. Ошибка та же. В инете пишут, что в основном из-за того, что переменные или функции называются random. Но это не тот случай. Помогите, плиз, уже второй день мучаюсь

import random
a = int(input())
b = int(input())
c = int(input())
random.choiсe([a, b, c])

5fbd4c650f39a038294477.png

As you may know from my previous posts, I’m learning Python. And this time I have a small error which I think is with this build of Python itself. When using the following:

import random
number = random.randint(1,10000)

Python gives me this error:

File "CUsersnameDocumentsPythonrandom.py", line 5, in (module)
  print random.random()
TypeError: 'module' object is not callable

Every time I try to run it. Me no understand. Any help would be much appreciated!

EDIT: The two lines of code I’m trying to run:

import random
print random.randint(1,100)

That’s it. And it gives me the same error.

Студворк — интернет-сервис помощи студентам

версия питона 3.6, IDE PyCharm
не могу пользоваться рандомом

Python
1
2
3
4
5
import random
 
random.seed([X], version=2)
a = 3
print (a)

выдает ошибку:
Traceback (most recent call last):
File «D:/aaa/pyton/venv/random.py», line 1, in <module>
import random
File «D:aaapytonvenvrandom.py», line 4, in <module>
random.seed([X], version=2)
AttributeError: module ‘random’ has no attribute ‘seed’

а без 3 строки выводит значение а 2 раза

Python
1
2
3
4
import random
 
a = 3
print (a)

3
3

вопрос: что не так? не правильное подключение модуля? или его вообще у меня нет?

If you are working with Python and trying to use the random library, you may encounter the “NameError: name ‘random’ is not defined” error. In this tutorial, we will explore why this error occurs and the steps required to fix it such that your Python code can successfully run without errors.

how to fix nameerror name random is not defined in python

We will cover common causes of the error and provide solutions to help you get your code up and running quickly. So, let’s get started!

Why does the NameError: name 'random' is not defined error occur?

This error occurs when you try to use the random library in your Python code, but Python cannot find the random module in its namespace. The following are some of the scenarios in which this error usually occurs.

  1. You have not imported the random module.
  2. You have imported the random module using a different name.

The random library in Python is a built-in module that provides a suite of functions for generating random numbers. It can be used to generate random integers, floating-point numbers, and sequences such as lists and tuples. It is commonly used in games, simulations, and statistical analysis. Since this library is a built-in library in Python, you don’t need to separately install it. You can import it and start using it.

Let’s now look at the above scenarios in detail.

The random module is not imported

It can happen that you are trying to use the random module without even importing it. This is because Python does not recognize the random library and its functions until it is imported into the code.

For example, let’s try to use the random module without importing it and see what we get.

# note that random is not imported

# generate a random integer between 1 and 10
print(random.randint(1, 10))

Output:

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[1], line 4
      1 # note that random is not imported
      2 
      3 # generate a random integer between 1 and 10
----> 4 print(random.randint(1, 10))

NameError: name 'random' is not defined

We get a NameError stating that the name random is not defined. To use the random library, you need to import it first.

import random

# generate a random integer between 1 and 10
print(random.randint(1, 10))

Output:

4

Here, we are importing the random module first and then using it to generate a random integer between 1 and 10. You can see that we did not get any errors here.

You can also get a NameError if you are importing only specific parts of the library and then trying to access the entire random library. For example –

from random import randint

# generate a random integer between 1 and 10
print(random.randint(1, 10))

Output:

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[1], line 4
      1 from random import randint
      3 # generate a random integer between 1 and 10
----> 4 print(random.randint(1, 10))

NameError: name 'random' is not defined

We get a NameError here because we are importing only the randint() function from the random library but we are trying to access the entire library. To resolve the above error, either only use the specific method imported or import the random library altogether.

The random module is imported using a different name

If you import the random module using a different name, for example import random as rnd, and then try to use the name “random” to use it, you will get a NameError because the name “random” is not defined in your current namespace.

Let’s look at an example.

import random as rnd

# generate a random integer between 1 and 10
print(random.randint(1, 10))

Output:

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[1], line 4
      1 import random as rnd
      3 # generate a random integer between 1 and 10
----> 4 print(random.randint(1, 10))

NameError: name 'random' is not defined

We get a NameError: name 'random' is not defined. This is because we have imported the random module with the name rnd but we’re trying to use it using the name random.

To fix this error, you can either access random using the name that you have used in the import statement or import random without an alias.

import random as rnd

# generate a random integer between 1 and 10
print(rnd.randint(1, 10))

Output:

9

In the above example, we are importing random as rnd and then using rnd to access the random module’s methods.

Alternatively, as seen in the example in the previous section, you can import random without any aliases and simply use random to avoid the NameError.

Conclusion

In conclusion, encountering a NameError: name 'random' is not defined error can be frustrating, but it is a common issue that can be easily fixed. By ensuring that the random module is imported correctly and that the correct syntax is used when calling its functions, you can avoid this error and successfully execute your code.

You might also be interested in –

  • How to Fix – NameError name ‘math’ is not defined
  • How to Fix – NameError: name ‘scipy’ is not defined
  • How to Fix – NameError: name ‘numpy’ is not defined
  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

Are you using the built-in functions of the random library but getting the “NameError: name ‘random’ is not defined” error?

Python has provided us with many built-in but helpful libraries that we can utilize to do specific tasks. One of these helpful libraries is random; it helps generate random numbers from a given range or choose a random element of an iterable like lists, tuples, strings, etc.

In this article, we’ll discuss what is the “NameError: name ‘random’ is not defined” error and how to fix it. For example, to utilize the built-in libraries of Python, you first need to install the required dependencies and then import them into your current program to work correctly.

Let’s first discuss what is random in Python and how it works. 

Table of Contents
  1. What is Random in Python?
  2. What is the the “NameError: Name ‘Random’ Is Not Defined” Error in Python?
  3. How to Fix the “NameError: Name ‘Random’ is Not Defined” Error in Python?

Random is a built-in library in Python that allows you to generate pseudo-random numbers. It performs different operations like choosing a random number from a given iterable and shuffling it.

The following are the different modules of Random in Python that we can use to perform different mathematical operations:

Method Description
seed() It is used to initialize a random number generator.
getstate()  It returns the current internal state of the random number generator.
setstate() It restores the state of the random number generator to the specified state.
getrandbits() It returns a number that represents random bits.
randrange() It returns a random number within a defined range.
randint() It returns a random integer within a defined range.
choice() It returns a random element from a defined iterable like list, tuple, or string.
choices() It returns a list by randomly selecting elements from a defined iterable like a list, tuple, or string.
shuffle() It is used to shuffle the order of elements of a list, string, or tuple. 
Sample() It returns a random sublist from a list.
random() It returns a float number between 0 and 1.
uniform() It returns a random float number between a defined range.
triangular() It returns a random float number between a given range, and you can also set a mode parameter to specify a midpoint between parameters.
betavariate() Depending on the beta distribution, it returns a random float number in the range of 0 and 1.
expovariate() It returns a random float number depending on the exponential distribution. 
gammavariate() It returns a random float number depending on the gamma distribution.
gauss() It returns a random float number depending on the gaussian distribution.
logonormvariate() This function returns a random float number depending on the log-normal distribution.
normalvariate() It returns a random float number depending on the normal distribution.
vonmisesvariate() It returns a random float number depending on the von mises distribution.
paretovariate() It returns a random float number depending on the Pareto distribution.
weibullvariate() It returns a random float number depending on the Weibull distribution. 

What is the the “NameError: Name ‘Random’ Is Not Defined” Error in Python?

In Python, we face the NameError when a variable or a function is not defined but used somewhere in your python program. For example, the NameError name random is not defined in Python in a similar case. Let’s see an example and understand the cause of this error.

Code

# generate a random integer number between 1-10

n1 = random.randint(1, 10)

print(n1)

Output

Fix "NameError: Name 'Random' Is Not Defined" in Python

How to Fix the “NameError: Name ‘Random’ is Not Defined” Error in Python?

To fix the “NameError: name ‘random’ is not defined” error in Python, you must first install the random library into your machines and then import it into your current program.

To install the random library, we’ll pip command. And to install it, go to your Command Line Interface (CLI) and enter the following command:

Command

pip install random

This command will install the random library into your local machines now, and you can easily import it into your current Python program. Let’s see how it works after installing and importing the library.

Code

# importing library

import random




# generate random integer numbers between 1-10

n1 = random.randint(1, 10)

n2 = random.randint(1, 10)




print("The first random number is ", n1)

print("The second random number is ", n2)

Output

The first random number is 3

The second random number is 7

Congrats! We have finally resolved the NameError. Now, we can use the numerous functions of the random library in our Python program.

Conclusion

To conclude the article on how to fix the “NameError: name ‘random’ is not defined” error in Python, we have discussed the random library and its numerous helpful functions of it. Furthermore, we have discussed the cause of these errors and how to fix them by installing and importing the random library.

Let’s have a quick recap of the topics discussed in the article.

  1. What is random in Python?
  2. What are the different functions of the random library in Python?
  3. What is the “NameError: name ‘random’ is not defined” error?
  4. How to install the random library in Python?
  5. How to fix the “NameError: name ‘random’ is not defined” error in Python?

Let’s do a quick exercise 💻, execute any of the above functions of the random library, and comment on the output.

Zeeshan is a detail-oriented software engineer and technical content writer with a Bachelor’s in Computer Software Engineering and certifications in SEO and content writing. Thus, he has a passion for creating high-quality, SEO-optimized technical content to help companies and individuals document ideas to make their lives easier with software solutions. With over 150 published articles in various niches, including computer sciences and programming languages such as C++, Java, Python, HTML, CSS, and Ruby, he has a proven track record of delivering well-researched and engaging technical content.

To fix the NameError: name ‘random’ is not defined in Python, you can use the following: import the random module before using it or use the numpy.random module. Please read the following article for details.

Python provides a random module that is extremely easy to deal with random numbers. The Random module implements a pseudo-random number generator and contains functions that allow us to deal directly with randomness.

‘NameError’ is an error when you use a variable, function, or module that is not declared or you are not using it properly.

NameError: name ‘random’ is not defined happens because you don’t import the random module before using it.

Example:

# Use the random() function
result = random.random()
print(result)

Output:

Traceback (most recent call last):
  File "code.py", line 2, in <module>
    result = random.random()
NameError: name 'random' is not defined

How to solve the NameError: name ‘random’ is not defined in Python?

Import the “random” module

Example:

  • Import requests from random Python packages (this is an important step you need to remember as it is the cause of this error).
import random

# Use the random() function
result1 = random.random()
print('Random output from random() function:', result1)

# Use the randint() function
result2 = random.randint(0,5)
print('Random output from randin() function:', result2)
 
# Use the randrange() function
result3 = random.randrange(2,7,2)
print('Random output from randrange() function:', result3)

Output:

Random output from random() function: 0.6993824842072576
Random output from randin() function: 5
Random output from randrange() function: 6

The random.randint() method takes two arguments, a range from 0 to 5, and returns a random number from that range.

The random() method generates a random float in the range (0.0, 1.0).

The random.randint() method takes two arguments representing the range from which the method draws a random integer.

Import random from the numpy module

You can use the numpy.random module to solve this problem.

Example:

from numpy import random

# Use the numpy.randint() function
result1 = random.randint(2, size=10)
print('Random output from numpy.randint() function:', result1)

# Use the numpy.rand() function
result2 = random.rand(3,2)
print('Random output from numpy.rand() function:', result2)

# Use the numpy.random() function
result3 = random.random(3)
print('Random output from numpy.random() function:', result3)

Output:

Random output from numpy.randint() function: [0 0 1 0 1 0 1 0 0 0]
Random output from numpy.rand() function: 
[[0.74079175 0.13131399]
 [0.16306477 0.04369934]
 [0.530455 0.90342889]]
Random output from numpy.random() function: [0.9458757 0.14450404 0.3792123 ]

In the example above:

  • The function numpy.random.randint returns a numpy array of random integers from low (inclusive) to high (exclude). 
  • numpy.random.rand returns a numpy array of random values ​​in a given shape.
  • numpy.random.random returns a numpy array of random numbers in the range [0.0, 1.0).

Summary

I have shown the causes and given some solutions to fix the NameError: name ‘random’ is not defined in Python. This is a pretty simple bug in Python. I hope you can fix it as soon as possible. Thanks for reading!

Maybe you are interested:

  • NameError: name ‘true’ is not defined in Python
  • NameError: name ‘reduce’ is not defined in Python
  • NameError: name ‘json’ is not defined in Python

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Уведомления

  • Начало
  • » Центр помощи
  • » Не работает рандом!

#1 Сен. 3, 2016 12:43:28

Не работает рандом!

В программе PyScripter не работает ничего, что связано с библиотекой или функцией random.
Самое странное, что в стандартном IDLE всё работает
Отказыватья от PyScripter’a не собираюсь — очень удобная софтина, нужно решение проблемы конкретно с этой прогой (если что, я студент-новичек)

Прикреплённый файлы:
attachment 2.png (32,1 KБ)

Офлайн

  • Пожаловаться

#2 Сен. 3, 2016 12:45:06

Не работает рандом!

Доказательство, что на стандартном IDLE всё работает

Прикреплённый файлы:
attachment 1.png (11,9 KБ)

Офлайн

  • Пожаловаться

#3 Сен. 3, 2016 16:41:26

Не работает рандом!

1. зачем вы обрезали низ картинки с пискриптером. Не видно какой питон запустился.
2. Вы показали что random не работает. Но не показали работает что-то еще или нет.

Может мои знания устарели с прошлой недели, но студенты пробовали Pyscripter не поддерживает пока версию питона 3.5. Версию питона и пискриптера огласите пожалуйста.

3. Из общих соображений крайне не рекомендую помещать скрипты в папку с кириллицей и оставлять название файла Модуль1

Офлайн

  • Пожаловаться

#4 Сен. 3, 2016 17:58:01

Не работает рандом!

doza_and
1. зачем вы обрезали низ картинки с пискриптером. Не видно какой питон запустился.2. Вы показали что random не работает. Но не показали работает что-то еще или нет.Может мои знания устарели с прошлой недели, но студенты пробовали Pyscripter не поддерживает пока версию питона 3.5. Версию питона и пискриптера огласите пожалуйста.3. Из общих соображений крайне не рекомендую помещать скрипты в папку с кириллицей и оставлять название файла Модуль1

Прикреплённый файлы:
attachment 2016-09-03 (2).png (307,3 KБ)

Офлайн

  • Пожаловаться

#5 Сен. 3, 2016 17:59:36

Не работает рандом!

doza_and
1. зачем вы обрезали низ картинки с пискриптером. Не видно какой питон запустился.2. Вы показали что random не работает. Но не показали работает что-то еще или нет.Может мои знания устарели с прошлой недели, но студенты пробовали Pyscripter не поддерживает пока версию питона 3.5. Версию питона и пискриптера огласите пожалуйста.3. Из общих соображений крайне не рекомендую помещать скрипты в папку с кириллицей и оставлять название файла Модуль1

Делал для себя вот такую игру(в русской версии забыл сменить utf8, пока переводить лень) до сегодня работала нормально Теперь зависает имеено на Рандоме

Прикреплённый файлы:
attachment 2016-09-03 (4).png (137,2 KБ)

Офлайн

  • Пожаловаться

#6 Сен. 3, 2016 18:00:31

Не работает рандом!

doza_and
1. зачем вы обрезали низ картинки с пискриптером. Не видно какой питон запустился.2. Вы показали что random не работает. Но не показали работает что-то еще или нет.Может мои знания устарели с прошлой недели, но студенты пробовали Pyscripter не поддерживает пока версию питона 3.5. Версию питона и пискриптера огласите пожалуйста.3. Из общих соображений крайне не рекомендую помещать скрипты в папку с кириллицей и оставлять название файла Модуль1

ПС все папки на английском

Офлайн

  • Пожаловаться

#7 Сен. 3, 2016 18:37:35

Не работает рандом!

doza_and
1. зачем вы обрезали низ картинки с пискриптером. Не видно какой питон запустился.2. Вы показали что random не работает. Но не показали работает что-то еще или нет.Может мои знания устарели с прошлой недели, но студенты пробовали Pyscripter не поддерживает пока версию питона 3.5. Версию питона и пискриптера огласите пожалуйста.3. Из общих соображений крайне не рекомендую помещать скрипты в папку с кириллицей и оставлять название файла Модуль1

Выяснил, что рандом работает, а вот все его “дополнения”(забыл как по-научному) — нет

Прикреплённый файлы:
attachment error.png (10,7 KБ)

Офлайн

  • Пожаловаться

#8 Сен. 3, 2016 22:51:10

Не работает рандом!

Сделайте

 import random
print(random.__file__)
print(sys.path)
print(os.getcwd())

Складывается впечатление что у вас random это что-то другое. Например вы создали свой файл random.py и забыли.

Да я понял. У вас два питона. Картинка с IDLE не представительна. Там дугой питон — 3.5

Офлайн

  • Пожаловаться

  • Начало
  • » Центр помощи
  • » Не работает рандом!

Вопрос:

Как вы можете узнать из моих предыдущих сообщений, я изучаю Python. И на этот раз у меня есть небольшая ошибка, которая, как мне кажется, связана с этой сборкой самого Python. При использовании следующего:

import random
number = random.randint(1,10000)

Python дает мне эту ошибку:

File "CUsersnameDocumentsPythonrandom.py", line 5, in (module)
print random.random()
TypeError: 'module' object is not callable

Каждый раз, когда я пытаюсь запустить его. Я не понимаю. Любая помощь будет высоко оценена!

EDIT: две строки кода, которые я пытаюсь запустить:

import random
print random.randint(1,100)

Что это. И это дает мне ту же ошибку.

Лучший ответ:

Именовав ваш script random.py, вы создали конфликт имен с стандартным библиотечным модулем random.

При попытке запустить script каталог, содержащий script, будет добавлен в начало пути импорта модуля. Поэтому, когда ваш script делает import random, вы фактически запускаете вторую копию script в качестве модуля random.

Когда модуль random работает import random, это означает, что random.random также будет ссылкой на ваш модуль. Поэтому, когда вы пытаетесь вызвать стандартную библиотечную функцию random.random(), вы фактически пытаетесь вызвать объект модуля, в результате чего вы получили сообщение.

Если вы переименуете свой script в другое, проблема должна исчезнуть.

Ответ №1

Я использую Pycharm, и мне пришлось сделать дополнительный шаг, чтобы импортировать методы from random. В моем случае:

import random
from random import choice

Ответ №2

Даже я столкнулся с той же проблемой. Я переименовал мой файл python из random.py в shuffle.py. Это не сработало. Потом я сменил версию, потом все заработало. Это может немного помочь. Версия Python: 3.6.7 заменить импорт случайным; импортировать random2;

Понравилась статья? Поделить с друзьями:
  • Python ошибка math domain error
  • Python ошибка killed
  • Python ошибка int object is not callable
  • Python ошибка eol while scanning string literal
  • Python ошибка encoding