CS50P 完全按照讲师的代码编写后语法无效

问题描述 投票:0回答:1

我尝试从此处的 CS50P 视频学习 Python https://youtu.be/-7xg8pGcP6w?si=N0TVaGfgLOWrXTqc&t=3264

准确输入代码,结果是错误

students = [
    {"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
    {"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
    {"name": "Ron", "house": "Gryffindor", "patronus": "Jack russel terrier"},
    {"name": "Draco", "house": "Slytherin", "patronus": None}
]
for student in students:
    print(student["name"], student["house"], student["patronus"])

给出的错误:

Python 3.12.0 (main, Nov  1 2023, 16:31:09) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>     {"name": "Hermione", "house": "Gryffindor", "Patronus"}
  File "<stdin>", line 1
    {"name": "Hermione", "house": "Gryffindor", "Patronus"}
IndentationError: unexpected indent
>>> 
>>> python hogwarts.py
  File "<stdin>", line 1
    python hogwarts.py
           ^^^^^^^^

已经重新检查了好几次了,但似乎找不到哪里做错了

请帮忙

我尝试重新检查讲师给出的代码,我认为这已经完全相同,但仍然导致错误

更新: 使用播放按钮运行代码,仍然导致错误:

SyntaxError: invalid syntax
>>> cd /workspaces/150403671
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'cd' is not defined. Did you mean: 'id'?
>>> /usr/local/bin/python /workspaces/150403671/hogwarts.py
  File "<stdin>", line 1
    /usr/local/bin/python /workspaces/150403671/hogwarts.py
    ^
SyntaxError: invalid syntax
python cs50
1个回答
0
投票

您当前处于 Python 交互式 shell 中,它允许您一次执行一行 Python 代码。

您可以在交互模式下运行给定的代码。它看起来像这样:

Python 3.12.0 (main, Nov  1 2023, 16:31:09) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>students = [
    {"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
    {"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
    {"name": "Ron", "house": "Gryffindor", "patronus": "Jack russel terrier"},
    {"name": "Draco", "house": "Slytherin", "patronus": None}
]
>>> for student in students:
    print(student["name"], student["house"], student["patronus"])
Hermione Gryffindor Otter
Harry Gryffindor Stag
Ron Gryffindor Jack russel terrier
Draco Slytherin None
>>>

或者,使用

exit()
退出交互模式,并使用完整代码创建一个名为 hogwarts.py 的文件。然后从终端提示符(不是 Python 交互模式)输入
python <path_to_file>\hogwarts.py
替换为实际路径。

© www.soinside.com 2019 - 2024. All rights reserved.