-1

In IDLE, I write a function and intend to return a value. but it can't return

>>> def grade(value):
    if value > 100:
        return (value=100)
    if value <0:
        return (value=0)

SyntaxError: invalid syntax

why can't return? but when I change to

value = 100
return value

It can work

4
  • 1
    just write return 100 and return 0. you cannot have assignments (=) in return statements. Also be careful of your indentation
    – Ma0
    Jul 19, 2016 at 14:36
  • 3
    It doesn't really make any sense to return an assignment, that's why. When you return the function is over, so there's really no point in assigning to anything as it will never be available.
    – jonrsharpe
    Jul 19, 2016 at 14:38
  • Because allowing assignment statements to be used as an expression leads to pernicious bugs. Compare return value == 1 versus return value = 1.
    – Dunes
    Jul 19, 2016 at 14:45
  • @jonrsharpe Not that I am advocating for this in any way, but there is one scenario that the assignment would have an effect: if you wish to both return a value and set a global variable to that value.
    – reo katoa
    Jun 10, 2017 at 0:12

1 Answer 1

7

In a return statement, only an expression can come after the "return".

return_stmt ::= "return" [expression_list]

An assignment is a statement. You can't put a statement after "return", because a statement isn't an expression.

Consider skipping the assignment entirely. Just return will suffice:

return 100

Not the answer you're looking for? Browse other questions tagged or ask your own question.