问题
a = input()
b = input()
print(a+b)
This can be written as
print(input()+input())
and it works.
How does it work? Where are the inputs are stored temporarily?
回答1:
Premise: input()
is just a normal function that blocks until the user types something in. Once that is done, the data is evaluated and returned.
With that set aside, your statement is composed of several parts:
print(...)
is a function call that prints the result of the expression that is between its parentheses.
The expression then is input() + input()
. Since the operator()
has a higher precedence than operator+
, the two input()
calls will be evaluated before the sum.
The result of an input()
is an unnamed temporary variable that exists only until the full expression is evaluated. Once the +
is executed, the temporary variables are effectively lost (and will be garbage collected eventually).
回答2:
Don't forget that input itself is a function, hence the value is being stored as a process part of the function itself. The output is a simple return, hence why you can freely call the function without parameters, and it separates it, too.
def input(*kwargs):
eval(raw_input(prompt))
Just because it doesn't look like a complex function doesn't mean it isn't.
https://docs.python.org/2/library/functions.html#input
回答3:
input() returns input value from prompt.
It is possible to do so by returning immediately rather than saving the temporary repository.
来源:https://stackoverflow.com/questions/53723533/how-printinput-input-works-in-python-without-variable-assignment