lisp里每个表达式均有值,而python3里为什么这种很平常的表达式却没有返回值呢?
<code class="language-python"><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
</code>
楼上的各位解释的已经很清楚了,总结一下就是:<code class="language-c"><span class="cp">#include<stdio.h></stdio.h></span>
<span class="kt">void</span> <span class="nf">main</span><span class="p">(){</span>
<span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">200</span><span class="p">;</span>
<span class="k">if</span><span class="p">(</span><span class="n">x</span> <span class="o">==</span> <span class="mi">1000</span><span class="p">)</span>
<span class="n">printf</span><span class="p">(</span><span class="s">"true"</span><span class="p">);</span>
<span class="k">else</span>
<span class="n">printf</span><span class="p">(</span><span class="s">"false"</span><span class="p">);</span>
<span class="p">}</span>
</code>
你要理解为b=a=1是一个语句,而不是表达式。
<code class="language-text">In [1]: def foo():
...: a = b = 1
...:
In [2]: from dis import dis
In [3]: dis(foo)
2 0 LOAD_CONST 1 (1)
3 DUP_TOP
4 STORE_FAST 0 (a)
7 STORE_FAST 1 (b)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
</code>
赋值语句没有返回值,所以不是表达式,这是因为赋值语句不需要返回值, Python 既不是 C 也不是 Lisp。<code class="language-text">assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)
</code>
为什么在python3里b=a=1是合理表达式
链式赋值只是一种语法结构 他并不是跟cpp一样"把1赋给a 再把a的值赋给b"而print(a=1)却不是
这句话的意思是把1赋给print的形参a 而不是像cpp那样“把1赋给局部变量a 再把a的值传进去”a=1为什么没有返回值
a=1在cpp里面是表达式(expression) 在py里面叫语句(statement)<code class="language-pytb"><span class="x">print(a=1)</span>
<span class="x">--------------------------------------------------------------------------</span>
<span class="x">TypeError Traceback (most recent call last)</span>
<span class="x"><ipython-input-4-ab52a41c9aa5> in <module>()</module></ipython-input-4-ab52a41c9aa5></span>
<span class="x">----> 1 print(a=1)</span>
<span class="x">TypeError: 'a' is an invalid keyword argument for this function</span>
</code>
<code class="language-python"><span class="k">if</span><span class="p">(</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span> <span class="c">#do.... } </span>
</code>