qwert4321 qwert4321 - 1 month ago 13
Python Question

Variable assignment in python: The assignment x=23 yields error when running x./4

When I run the following program in python 2.7.5 I get

>>> x=23
>>> print x
23


Ok fine.

Similarly, type(x) is int.

When I run the following program:

>>> print 23./4
5.75


Still fine. But then when I run this final program:

>>> x=23
>>> print x./23
>>> File "<stdin>", line 1
print x./4
^SyntaxError: invalid syntax


i.e. I get a syntax error. But I can do other arithmetical operations with x treating it as though it were the integer 23; x+1 yields 24, x/23 yields 1 and so on. So what is going on here? p.s. this is my first post hopefully the formatting is ok.

Answer

Notice that the following program also fails:

x = 10
print x5

even though this program works:

print 105

If the above makes sense, then the only missing part here is understanding that 23. is a short for 23.0, it's a single entity, not two separate (23 and .).

If however my above example also seems not intuitive to you, then your understanding of variables is a little off, and I would recommend revisiting the chapter on variables in whichever textbook you are using.

Comments