Cortisol
Cortisol

Reputation: 15

Variable assignment in numpy not working?

I'm just starting to learn how to code, so this may seem like a stupid question, but I'm trying to build a simple program where the computer generates a random number and the user has 1 chance to get it right.

However, the program always gets stuck on this variable:

number = np.random.randint(low=1, high=10, size=1)

I don't know if this function can't be put as a variable (it works by itself, but not when assigned to "number"), but whenever I run it this appears:

  File "/Users/User/Desktop/Python/App.py", line 4, in <module>
    print("The number was " + number)
numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')```

Upvotes: 1

Views: 89

Answers (2)

wjandrea
wjandrea

Reputation: 33179

There are two problems here. Firstly number is not an int but a Numpy array containing an int. If you just omit the size argument it will give you an int.

number = np.random.randint(low=1, high=10)

Secondly you're trying to add a string with a Numpy array, which won't work. Same for adding a string and an int (TypeError: Can't convert 'int' object to str implicitly). So instead of adding, put number as a separate argument to print and it will automatically get converted to a string and separated by a space.

print("The number was", number)

Also, Numpy is overkill here when you could use the random module from the standard library. Confusingly, np.random.randint seems to be equivalent to random.randrange, not random.randint.

import random
number = random.randrange(1, 10)

Upvotes: 1

abhilb
abhilb

Reputation: 5757

You are trying to concatenate a string with a numpy ndarray You need to convert number to string.

>>> number = np.random.randint(low=1, high=10, size=1)
>>>
>>> print("test " + number)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U11') dtype('<U11') dtype('<U11')
>>>
>>> print("test" + str(number))
test[8]

Upvotes: 1

Related Questions