首页 > 解决方案 > 如何根据学生管理系统的用户输入在 python 中添加字典

问题描述

我的程序没有按预期工作,我认为它应该按用户询问的输入数量运行。此外,字典没有添加 ie 两次,它保持空白:

d={}
i=0
ent_inp=int(input('Enter #1 to add student\nEnter #2 to search student\nEnter #3 to del student\nEnter 4# to exit\n\nEnter your choice= '))
if ent_inp==1:
    howmany=int(input('How many student detail you want to enter: '))
    
    while i<=howmany:

        d['RollNum']=input('Enter the Roll Num: ')
        d['RollNum']={}
        d['RollNum']['Name']=input('Enter the Name: ')
        d['RollNum']['Marks']={}
        d['RollNum']['Marks']['English']=input('Enter the Marks of English: ')
        d['RollNum']['Marks']['Maths']=input('Enter the Marks of Maths: ')
        d['RollNum']['Marks']['Hindi']=input('Enter the Marks of Hindi: ')
        i=i+1
        continue
    print(d)

标签: pythonpython-3.x

解决方案


您将有更好的时间将您的逻辑拆分成这样的事情,也许:

  • input_student负责为单个学生索取信息;它将它作为字典返回。
  • main包含其余的逻辑,封装为一个函数,以防止意外引用全局变量。
    • for循环比在while已知范围内迭代要好。

您可以进一步重构它以使各种菜单条目(一旦您实现其余部分)单独的功能。

def input_student():
    student = {"Marks": {}}
    student["RollNum"] = input("Enter the Roll Num: ")
    student["Name"] = input("Enter the Name: ")
    student["Marks"]["English"] = input("Enter the Marks of English: ")
    student["Marks"]["Maths"] = input("Enter the Marks of Maths: ")
    student["Marks"]["Hindi"] = input("Enter the Marks of Hindi: ")
    return student


def main():
    students = []

    ent_inp = int(
        input(
            "Enter #1 to add student\n"
            "Enter #2 to search student\n"
            "Enter #3 to del student\n"
            "Enter 4# to exit\n\n"
            "Enter your choice= "
        )
    )
    if ent_inp == 1:
        howmany = int(input("How many student detail you want to enter: "))
        for i in range(howmany):
            students.append(input_student())
        print(students)


main()

推荐阅读