Python Forum

Full Version: "SyntaxError: invalid syntax" running code in Doing Math With Python b
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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 :-)
(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