Python函数参数写法疑问:为何用location='princeton'而非'location'='princeton'
location='princeton' Instead of 'location'='princeton' in Function Calls? Hey there! Great question—this is such a common mix-up when you're new to Python, so let's break this down step by step.
First, let's clarify what location='princeton' actually is
When you write location='princeton' in a function call like build_profile(..., location='princeton'), you're using a keyword argument. Here's what that means:
locationis the name of the parameter defined in thebuild_profilefunction (likedef build_profile(name, location, ...):).- Python uses this unquoted name to match the value directly to the correct parameter in the function definition. No quotes needed because it's referencing the parameter's identifier, not a string value.
Why 'location'='princeton' doesn't work
If you wrap location in quotes, Python interprets 'location' as a string literal. In Python, you can't assign a value to a string—strings are immutable, and this syntax makes no sense to the interpreter. Try running that line, and you'll get a SyntaxError because Python sees you trying to set a string equal to something, which isn't allowed.
For example:
# This will throw an error! build_profile('albert', 'location'='princeton')
The error message will look something like SyntaxError: expression cannot contain assignment, perhaps you meant "=="?—because Python thinks you might have confused assignment (=) with equality checking (==), but even that wouldn't make sense here.
A quick recap
- Keyword arguments use the parameter's actual name (no quotes) followed by
=and the value. This tells Python exactly which parameter your value should go to. - Quoting the name turns it into a string, which can't be assigned to a value in this context—it's not a valid parameter reference.
Keep asking these detailed questions as you learn—they're a great sign you're paying attention to how Python's syntax works!
内容的提问来源于stack exchange,提问作者Daniel Scan

