Python代码报错求助:缩进块缺失与get_student未定义问题
问题排查与解决
错误原因分析
- 「预期缩进块」错误:
class Student:定义后没有任何缩进的代码块,Python要求类定义后必须有缩进内容(哪怕是占位的pass),否则会触发语法错误。 - 「get_student 未定义」错误:
main函数中调用了get_student,但get_student的定义在main之后,Python解释器从上到下执行代码,执行到main里的调用时,还未读取到get_student的定义,因此报未定义错误。
修正后的代码
class Student: pass # 用pass作为类的占位内容,解决缩进块问题 def get_student(): student = Student() student.name = input("name: ") student.house = input("house: ") return student def main(): student = get_student() print(f"{student.name} from {student.house}") if __name__ == "__main__": main()
优化拓展(可选)
如果后续要给Student类添加初始化逻辑,可以改成更规范的写法:
class Student: def __init__(self, name, house): self.name = name self.house = house def get_student(): name = input("name: ") house = input("house: ") return Student(name, house) def main(): student = get_student() print(f"{student.name} from {student.house}") if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者Adebayo Yusuf
相关产品推荐
相关产品推荐

