[Python Debugging] SyntaxError: non-default argument follows default argument & How Function Works in Python
Table of contents
def greet(msg="Good morning!", name):
return "Hi! " + name + ', ' + msg
print(greet("John")) # Syntax Error
print(greet("Mary", "How do you do?")) # Syntax Error
Look at the code above and think of why that would cause an error.
When you declare a function with arguments, the arguments can be comprised of:
- Only default arguments
def greet(msg="Good morning!", name = "John"):
- Only arguments without any default values assigned
def greet(msg, name):
- Default arguments to the back
def greet(name, msg="Good morning!"):
Refer to this image below to understand how python interprets functions.
Conclusion
Therefore, you should look at the arguments of your function if you faced SyntaxError: non-default argument follows default argument
. Re-arrange the order of the arguments or you can also do something like this:
def greet(msg, name):
return "Hi! " + name + ', ' + msg
print(greet(name = 'John', msg='Good morning!'))
# Hi! John, Good morning!
This allows you to set which argument receives which value, which enhances the readbility as well as helps you to avoid errors.
Reference
https://levelup.gitconnected.com/5-types-of-arguments-in-python-function-definition-e0e2a2cafd29