I need to print a tuple of all these numbers when the user enters 1 or more numbers. This is how I did it:
print (eval ("(" + input ("Enter 2 numbers:") + ")"))
And this is the error that the interpreter gives when entering numbers 2 and 16:
Traceback (most recent call last): File "D: \ Programming \ Python Projects \ USE_TEST_1.py", line 3, in & lt; module & gt; print (eval ("(" + input ("Enter 2 numbers:") + ")")) File "& lt; string & gt;", line 1 2 16 ^ SyntaxError: unexpected EOF while parsing
Answer 1, authority 100%
The error message does not show the
() brackets for you, so there is an error in the
input () function. You can verify this by calling
input () on a separate line.
What you get a
SyntaxError by calling the
input () function indicates that you are running the code using Python 2, not Python 3, despite what is specified in question labels. In Python 2,
input () itself works in a similar way to
eval (raw_input ()) .
SyntaxError you get because to create a tuple of two numbers, you need to a comma . However, the parentheses are not needed at all unless you want to create an empty tuple:
Here’s a minimal change to your code in the question to “print a tuple of all these numbers” (but before using the example, read the “eval () is evil” section below):
#! / usr / bin / env python2 print input ("Enter 2 comma-separated numbers:")
#! / usr / bin / env python3 print (eval (input ("Enter 2 comma-separated numbers:")))
If you enter:
then both examples will print in response:
eval () is evil
Of course, the user of the program is free to specify
__import __ ('os'). remove ('important file') instead of numbers. Therefore, a safer way is to read the string and recognize the given input format manually, for example:
#! / usr / bin / env python2 print tuple (map (int, raw_input ("Enter 2 comma-separated numbers:") .split (',')))
#! / usr / bin / env python3 print (tuple (map (int, input ("Enter 2 comma-separated numbers:") .split (','))))
The results are the same as for the previous examples.
When accepting keyboard input, you should expect input errors, so it’s good to catch exceptions and retry to retrieve the numbers by typing an informative error message. See Asking the user for input until they give a valid response .