That assertion is checking that the type of b should be āfloatā in python. So what type is your b value?
Consider the following two statements in python:
x = 42
y = 42.
You might think that those two statements are equivalent, but they are not. In some other languages (e.g. MATLAB), they might be equivalent, but they are not in python and thatās what we are working with here. Try running the following block of statements and watch what happens:
x = 42
y = 42.
print(f"type(x) = {type(x)}")
print(f"type(y) = {type(y)}")
Thanks for the quick response.
I tried the following for my function
print(f"type(b) = {type(b)}")
Output : type(b) = <class āfloatā>
Code : That I was trying :
b = 0
assert(isinstance(b, float) or isinstance(b, int))
Are you saying itās working now and that you changed the code from what you show there? Because the code you are showing would fail that assertion, right? That is the point of my previous example.
Hi, it looks like he is suggesting changing the assert statement so b could be either a float or an int.
@Ptand2 you are not supposed to change the assert part, thatās correct, as suggested by @paulinpaloalto you need to change your code so b is defined as a float. Please use the hint he provided.
Thanks, Alberto! I missed his proposed change. I didnāt think about it because that test cell is not modifiable in any case. There probably would be no real harm in using the more permissive version of the assertion in this particular case, but they are trying to make a point here. In python you have to be careful because you can have problems with type issues because of the fact that the default numeric type in python is an integer. Hereās an example:
x = np.array([[2, -1, 5]])
print(x.dtype)
y = np.array([[0.1, 2.1, -3.1]])
print(y.dtype)
x -= y
If you run that, hereās what happens:
int64
float64
---------------------------------------------------------------------------
UFuncTypeError Traceback (most recent call last)
<ipython-input-6-98a07897ec34> in <module>
3 y = np.array([[0.1, 2.1, -3.1]])
4 print(y.dtype)
----> 5 x -= y
UFuncTypeError: Cannot cast ufunc 'subtract' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
The point is that it throws that error because the semantics of the āin placeā assignment require that the type of the RHS to be coerced to the type of the LHS and to do that would lose information (coercing a float to an int). So it throws rather than doing the coercion.