How do I calculate 1+2+3+4+5
on Python 3?
n = int(input())
print(n)
The above code works in Python 2 however it doesn't work in Python 3.
Input
1+2+3+4+5
Output
15
Thank you.
How do I calculate 1+2+3+4+5
on Python 3?
n = int(input())
print(n)
The above code works in Python 2 however it doesn't work in Python 3.
Input
1+2+3+4+5
Output
15
Thank you.
Try ast.literal_eval
like this in Python 3:
from ast import literal_eval
n = input()
print(literal_eval(n))
Example:
1+2+3+4+5
15
The reason it works in Python 2 is because in Python input
was the same as eval
in Python 3, to have a regular input in Python 2 you have to use raw_input
.
Python's eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you're trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.
a = eval(input())
print(a)