提问人:Budi 提问时间:11/17/2023 最后编辑:Budi 更新时间:11/17/2023 访问量:59
CS50P 完全按照讲师的代码编写后语法无效 [已关闭]
CS50P invalid syntax after write exactly as the lecturer's code [closed]
问:
我尝试从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
答:
1赞
nigh_anxiety
11/17/2023
#1
您当前位于 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
>>>
或者,退出交互模式,并使用完整代码创建名为 hogwarts.py 的文件。然后,在终端提示符(非 Python 交互模式)中键入,将 <path_to_file> 替换为实际路径。exit()
python <path_to_file>\hogwarts.py
核心 CS50 课程是围绕 CS50 GitHub CodeSpace 的使用而设计的。此处的设置说明 如果可能,您应该使用 CS50 CodeSpace。此处的设置说明: https://cs50.harvard.edu/python/2022/psets/0/
有关 CS50 的 VsCode 的视频短片:https://cs50.harvard.edu/python/2022/shorts/visual_studio_code_for_cs50/
评论
>>>
$
%
python