search
HomeBackend DevelopmentPython Tutorial为什么在python3里b=a=1是合理表达式,而print(a=1)却不是。a=1为什么没有返回值?

lisp里每个表达式均有值,而python3里为什么这种很平常的表达式却没有返回值呢?

回复内容:

首先,因为你在用C/C++的思维理解python。

没有就是没有,返回值的提法也不对,返回值是函数的结果。准确说应该是表达式值。

语言的语法是人定义的,赋值是assignment statement,不是expression,所以没有值。

另外,在python里面function_name(var=????)是有特殊的语义的,它指的是function_name的var参数的实参是????。

例如
<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>
楼上的各位解释的已经很清楚了,总结一下就是:

python中赋值就是赋值,他不是一个表达式,也就不会返回一个表达式的值。

这样做的一个好处是让语法更加清晰。

在C中存在一个“行内赋值”的问题,举个栗子:你打算判断x的值是否等于1000, 如果等于1000则返回真,如果不等则返回假,正确的代码应该是:
<span class="cp">#include<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>
你要理解为b=a=1是一个语句,而不是表达式。
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   
赋值语句没有返回值,所以不是表达式,这是因为赋值语句不需要返回值, Python 既不是 C 也不是 Lisp。
即使有返回值的 Lisp ,返回值一般也是 '(),这就告诉你不要想用返回值做什么事,其实和 Python 的思想是一样的。
区别是 Python 用一个语法错误来防止程序员干蠢事而已。
Why does Python assignment not return a value?

链式赋值的逻辑不是先求值右侧的表达式再赋给左侧,仅仅是一种语法而已。下面可以看到,赋值的语句的解析显然不是递归的。
Simple statements
assignment_stmt ::=  (target_list "=")+ (expression_list | yield_expression)
为什么在python3里b=a=1是合理表达式
链式赋值只是一种语法结构 他并不是跟cpp一样"把1赋给a 再把a的值赋给b"
而是把1赋给b和a

而print(a=1)却不是
这句话的意思是把1赋给print的形参a 而不是像cpp那样“把1赋给局部变量a 再把a的值传进去”

a=1为什么没有返回值
a=1在cpp里面是表达式(expression) 在py里面叫语句(statement)
语句就像cpp的"return xxx;"一样 不必要有值
另外表达式的值也不叫返回值 因为Python语言的设计者认为赋值最重要的作用是其副作用,不应该像表达式那样有返回值.详见:docs.python.org/3/faq/d
  1. Python的赋值语句是没有返回值的,而且很多语言都没有,这并不是编程语言界的规定或者惯例。
  2. 你的那个
    <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>()</span>
    <span class="x">----> 1 print(a=1)</span>
    <span class="x">TypeError: 'a' is an invalid keyword argument for this function</span>
    
    <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>
    
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

How do you debug shebang-related issues?How do you debug shebang-related issues?Apr 30, 2025 am 12:17 AM

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

How do you remove elements from a Python array?How do you remove elements from a Python array?Apr 30, 2025 am 12:16 AM

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

What data types can be stored in a Python list?What data types can be stored in a Python list?Apr 30, 2025 am 12:07 AM

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

What are some common operations that can be performed on Python lists?What are some common operations that can be performed on Python lists?Apr 30, 2025 am 12:01 AM

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor