SyntaxError: non-default argument follows default argument in Python
Hi everyone, I am a beginner in Python and today I am learning about methods and arrays. I wrote some code as below:
def add_book(name, author, price = 0, publish_date):
return {'name': name, 'author': author, 'price': price, 'publish_date': publish_date}
store = []
store.append(add_book('Book 1', 'A', 100, "2022/01/10"))
store.append(add_book('Book 2', 'A', 130, "2022/03/10"))
store.append(add_book('Book 3', 'B', 170, "2022/03/10"))
for x in store:
print(x)
I create a method name add_book()
that helps return a dictionary and I will add it to an array. But when I ran the code above I got an exception SyntaxError: non-default argument follows default argument.
File "main.py", line 1
def add_book(name, author, price = 0, publish_date):
^
SyntaxError: non-default argument follows default argument
I'm using Python version 3.9.8 and Windows 11.
I appreciate your help.
-
r0
raphael seban Jun 22 2022
The error SyntaxError: non-default argument follows default argument is a compile error, you are wrong syntax.
Theory about method's param: Optional parameters have to appear behind non-optional parameters.
your
price
parameter is an optional parameter so it should be moved to the last. See the code below:def add_book(name, author, publish_date, price = 0): return {'name': name, 'author': author, 'price': price, 'publish_date': publish_date} store = [] store.append(add_book('Book 1', 'A', "2022/01/10")) store.append(add_book('Book 2', 'A', "2022/03/10", 200)) store.append(add_book('Book 3', 'B', "2022/03/10", 110)) for x in store: print(x)
#Output
{'name': 'Book 1', 'author': 'A', 'price': 0, 'publish_date': '2022/01/10'} {'name': 'Book 2', 'author': 'A', 'price': 200, 'publish_date': '2022/03/10'} {'name': 'Book 3', 'author': 'B', 'price': 110, 'publish_date': '2022/03/10'}
I hope this answer is helpful to you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.