-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

zijie lin
  • 17
  • 1
  • 3
  • 1
    just write `return 100` and `return 0`. you cannot have assignments **(=)** in `return` statements. Also be careful of your indentation – Ma0 Jul 19 '16 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 '16 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 '16 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 '17 at 00:12

1 Answers1

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
Kevin
  • 74,910
  • 12
  • 133
  • 166