PLEASE NOTE: This is NOT about the use of eval(), it is about the potential quality (or lack thereof) of a book it is used and taught in. SO already has countless threads ab
Yes, it's wrong. But I think I know why it's in there.
Lots of people use input()
in Python 2.x, which is a very unfortunately named function since it doesn't just read input, it also evaluates it. The converter 2to3
converts each use of input()
to eval(input())
, as you can see:
$ cat test.py
x = input("Enter your number: ")
$ 2to3 test.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored test.py
--- test.py (original)
+++ test.py (refactored)
@@ -1 +1 @@
-x = input("Enter your number: ")
+x = eval(input("Enter your number: "))
RefactoringTool: Files that need to be modified:
RefactoringTool: test.py
So my guess is that it is just a little sloppy. From the Amazon description:
This is the second edition of John Zelle's Python Programming, updated for Python 3.
I think someone ran 2to3
on all of the code samples without checking the output thoroughly enough. So yes, it was a mistake to use input()
in Python 2.x, and it was a mistake to use 2to3
without checking the output.