You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python学生名册脚本纠错求助:数组定义及5处错误排查

Python学生名册脚本错误修复指南

以下是代码中的5处错误及对应修复方案:

  • 错误1:array类型使用不当
    原代码第3行students=array(),array模块的array要求指定类型码,且仅能存储同类型基本数据,无法存储字典。应改为普通列表:

    students = []
    

    同时可移除无用的from array import array语句。

  • 错误2:函数参数拼写错误
    getFloat函数定义时参数名为promp(少字母t),但函数内部调用getString(prompt, field)时用的是prompt,导致参数未定义。修正函数定义:

    def getFloat(prompt, field):
    
  • 错误3:布尔值大小写错误
    Main函数中keepGoing=true,Python布尔值首字母必须大写,小写true会被视为未定义变量。修正为:

    keepGoing = True
    
  • 错误4:主函数调用大小写不匹配
    定义的主函数是Main()(首字母大写),但最后调用时写的是main()(小写),导致找不到函数。修正调用语句:

    Main()
    
  • 错误5:入口判断语句错误
    原代码if __name__=="__BC02.py__"不符合Python标准入口格式,应改为:

    if __name__ == "__main__":
    

修复后的完整代码

students = []

def getString(prompt, field):
    valid = False
    while valid == False:
        myString = input(prompt)
        if len(myString) > 0:
            valid = True
        else:
            print("The student's " + field + " cannot be empty. Please try again.")
    return myString

def getFloat(prompt, field):
    while True:
        try:
            fNum = float(getString(prompt, field))
            break
        except ValueError:
            print("That is not a valid number for " + field + ", please try again")
    return fNum

def addStudent():
    first = getString("Enter the student's first name: ", "first name")
    last = getString("Enter the student's last name: ", "last name")
    major = getString("Enter the student's major: ", "major")
    gpa = getFloat("Enter the student's GPA: ", "GPA")
    students.append({"first":first,"last":last,"major":major,"gpa":gpa})

def displayStudents():
    print("\nCollege Roster:")
    print("*************************************************************************")
    if len(students) == 0:
        print("There are no students to display.")
    else:
        print("First Name".ljust(20," ") + "Last Name".ljust(30," ") + "Major".ljust(15," ") + "GPA".ljust(6," "))
        for i in range(len(students)):
            print(students[i]['first'].ljust(20, " "), end="")
            print(students[i]['last'].ljust(30, " "), end="")
            print(students[i]['major'].ljust(15, " "), end="")
            print(str(students[i]['gpa']).ljust(6, " "))
    print("*************************************************************************")

def Main():
    keepGoing = True
    menu="""
*************************************************************************
College Roster System
*************************************************************************
Main Menu:
a) Enter a new Student
b) View all Students
c) Clear Students List
d) Exit
*************************************************************************
Choose an option: """
    while keepGoing:
        choice = input(menu)
        if choice != "":
            if choice.lower() == "a":
                addStudent()
            elif choice.lower() == "b":
                displayStudents()
            elif choice.lower() == "c":
                students.clear()
                print("\nThe list of students is cleared.")
            elif choice.lower() == "d":
                keepGoing = False
            else:
                print("\nThat is not a valid selection. Please try again.\n")
        else:
            print("\nYour selection cannot be empty. Please try again.\n")
    print("\nOkay, goodbye!!!")

if __name__ == "__main__":
    Main()

内容的提问来源于stack exchange,提问作者Matthew Burdick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:50:32