Suppose that:
h=[1,2,3]
There is operation N[expr]
in Mathematica that gives us:
N[h[0]]=1, N[h[1]]=2, N[h[2]]=3
and for example N[h[6]]=0
, is something like this in Python?
Suppose that:
h=[1,2,3]
There is operation N[expr]
in Mathematica that gives us:
N[h[0]]=1, N[h[1]]=2, N[h[2]]=3
and for example N[h[6]]=0
, is something like this in Python?
N[expr]
in mathematica gives you the numeric value oft an expression. This makes sense in mathematica, which dos symbolic math.
In Python you normally don't have symbolic expressions (unless using specialized libraries such as sympy).
You can convert objects to integers using int
. For example, int(2)
, int('2')
, or int(2.6)
result in the value 2.
Or you can convert to floating point using float
.
Accesing out-of-bound value in Python using [..]
operator in Python raises IndexError
.
>>> h = [1, 2, 3]
>>> h[0]
1
>>> h[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
By catching IndexError
, you can have similiar operation using a custom function:
>>> def N(sequence, index, fallback=0):
... try:
... return sequence[index]
... except IndexError:
... return fallback
...
>>> h = [1, 2, 3]
>>> N(h, 0)
1
>>> N(h, 1)
2
>>> N(h, 2)
3
>>> N(h, 6)
0
>>>
>>> N(h, 6, 9) # different fallback value other than 0
9