[Tutor] Why is it invalid syntax to have a particular dictionary value as an argument?

Dave Angel davea at davea.name
Mon Apr 6 18:31:16 CEST 2015


On 04/06/2015 10:54 AM, boB Stepp wrote:
> Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
>>>> d = {'n': 'Print me!'}
>>>> d
> {'n': 'Print me!'}
>>>> d['n']
> 'Print me!'
>>>> def func(d['n']):
> SyntaxError: invalid syntax
>>>> def func(d):
>          print d['n']
>
>>>> func(d)
> Print me!
>
> The plain text does not show it, but in the invalid syntax the "[" is
> highlighted red.
>
> Why is it invalid syntax to pass a particular dictionary value in a
> function? Or does it require a different form to do so?

You're getting confused between defining a function and calling one.

For Python 2.7, see:
 
https://docs.python.org/2/reference/compound_stmts.html#function-definitions


When defining a function, you provide (not pass) the formal parameters, 
and they must be simple names.  Those names will end up being local 
variables when the function is finally called.

(The only sort-of exception to this in 2.7 is when you define a default 
argument to a function.  In that case, the parameter still must be a 
valid python variable name, but the default value can be an arbitrary 
expression, as long as it's valid at the time of function definition.)


Once the function is being called, then you can use an arbitrary 
expression for your argument.  The results of that expression is bound 
to the formal parameter specified above.

Further reading:
https://docs.python.org/2/faq/programming.html#faq-argument-vs-parameter
https://docs.python.org/2/glossary.html#term-parameter
https://docs.python.org/2/glossary.html#term-argument


Now, it's possible that what you're trying to do is something that can 
be accomplished some other way.  So please elaborate on your purpose in 
using the syntax you did.  Or supply a small program that shows a 
function being defined and called, that would give meaning to the syntax 
you're trying.
-- 
DaveA


More information about the Tutor mailing list