Python3字典存储函数报错:SyntaxError: 'return' outside function 求助
Hey there! Welcome to programming and to asking questions—we’ve all stumbled over silly syntax bugs when we’re starting out, so no worries at all. Let’s break down what’s going wrong with your code and fix it step by step.
First, the Root Cause of the SyntaxError
That SyntaxError: 'return' outside function happens because your return car_dict line isn’t properly indented to be part of the make_car function. Python relies entirely on indentation to define code blocks, so any code that’s supposed to run inside the function needs to be indented consistently (usually 4 spaces) under the def line.
Second, a Hidden Spelling Bug
You also have a small typo: in the line 'manufacturer': manufacture.title(), you wrote manufacture instead of manufacturer (missing the final 'r'). This would cause a NameError once you fix the indentation, so we’ll tackle that too.
Here’s the Corrected Code
def make_car(manufacturer, model, **options): """Make a dictionary representing our cars.""" car_dict = { 'manufacturer': manufacturer.title(), 'model': model.title(), } for option, value in options.items(): car_dict[option] = value return car_dict our_forrester = make_car('subaru', 'forrester', color='black', all_wheel_drive=True, AC=True) print(our_forrester) our_tacoma = make_car('toyota', 'tacoma', color='dark green', four_wheel_drive=True, AC=True) print(our_tacoma)
What Changed?
- Indented the
return car_dictline so it’s clearly inside themake_carfunction (aligned withcar_dictand theforloop) - Fixed the typo from
manufacturetomanufacturerin the dictionary entry
If you run this corrected code, it should output the car dictionaries as expected without any errors. Happy coding!
内容的提问来源于stack exchange,提问作者Bill Starnes

