Python Forum
"SyntaxError: invalid syntax" running code in Doing Math With Python b - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: "SyntaxError: invalid syntax" running code in Doing Math With Python b (/thread-30738.html)



"SyntaxError: invalid syntax" running code in Doing Math With Python b - saucerdesigner - Nov-03-2020

Hello, I'm scratching my head trying to get the code in the book Doing Math With Python by Amit Saha on page 9 to work.

Python 3.8.5 (default, Jul 28 2020, 12:59:40)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> from fractions import Fraction
>>> try:
    a = float(input('Enter a number: '))
    #keyword except doesn't un-indent, I have to force it with a backspace
except ValueError:
    print('You entered an invalid number')
    Enter a number 3/4
    
SyntaxError: invalid syntax
>>>
What am I doing wrong? Wrong python version?

Regards,

David


RE: "SyntaxError: invalid syntax" running code in Doing Math With Python b - DeaD_EyE - Nov-03-2020

Hint: Use https://pypi.org/project/ipython/

You have to indent explicit by 4 spaces after the try and the except:
>>> try:
...     a = float(input('Enter a number: '))
... except ValueError:
...     print('You entered an invalid number')
...
Enter a number: 3/4
You entered an invalid number
>>>
Same with IPython repl:
In [1]: try:
   ...:     a = float(input('Enter a number: '))
   ...: except ValueError:
   ...:     print('You entered an invalid number')
   ...:
Enter a number: 3/4
You entered an invalid number

In [2]:
The benefit here is, that the indentation for multiline is made automatically.
You don't have to hit 4 times the space, if you use IPython. Also Tabulator is converted into 4 spaces :-)


RE: "SyntaxError: invalid syntax" running code in Doing Math With Python b - saucerdesigner - Nov-03-2020

(Nov-03-2020, 03:56 PM)DeaD_EyE Wrote: Hint: Use https://pypi.org/project/ipython/

You have to indent explicit by 4 spaces after the try and the except:
>>> try:
...     a = float(input('Enter a number: '))
... except ValueError:
...     print('You entered an invalid number')
...
Enter a number: 3/4
You entered an invalid number
>>>
Same with IPython repl:
In [1]: try:
   ...:     a = float(input('Enter a number: '))
   ...: except ValueError:
   ...:     print('You entered an invalid number')
   ...:
Enter a number: 3/4
You entered an invalid number

In [2]:
The benefit here is, that the indentation for multiline is made automatically.
You don't have to hit 4 times the space, if you use IPython. Also Tabulator is converted into 4 spaces :-)

Thank you! Evidently I don't yet know how to run IDLE, so I tried PyCharm Edu and it ran ok. Thanks again1