试图返回赋值的 SyntaxError [英] SyntaxError trying to return the value of assignment

查看:22
本文介绍了试图返回赋值的 SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有列表参数的函数,在它的主体内部我想通过以下代码修改传递的列表:

Suppose I have function with list parameter, and inside it's body I want to modify passed list, by this code:

spy = [0,0,7]

def replace_spy(lista):
    return lista[2]=lista[2]+1

但它显示了错误:SyntaxError: invalid syntax

推荐答案

赋值是一个语句,而不是一个表达式.它没有任何价值.所以你不能返回赋值的值.

Assignment is a statement, not an expression. It has no value. So you can't return the value of an assignment.

在允许这种事情的语言中,返回值到底应该是什么是不明确的,但是它们中的大多数——包括 C 和许多从 C 派生或受 C 启发的语言——都会给出lista[2]1 的新值.所以大概你想要这个:

Across languages that do allow this kind of thing, it's ambiguous what exactly the return value should be, but most of them—including C and the many languages derived from or inspired by C—would give you the new value of lista[2]1. So presumably you want this:

def replace_spy(lista):
    lista[2]=lista[2]+1
    return lista[2]

如果您想缩短内容,这会减少击键次数,而且可能更具可读性:

If you're looking to shorten things, this is fewer keystrokes, and probably more readable:

def replace_spy(lista):
    lista[2] += 1
    return lista[2]

<小时>

1.作为一个左值",但这在 Python 中没有意义.

这篇关于试图返回赋值的 SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆