How print(input() + input()) works in python ? Without variable assignment?

ⅰ亾dé卋堺 提交于 2021-02-19 08:44:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!