python - 如何根据学生管理系统的用户输入在 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)
解决方案
您将有更好的时间将您的逻辑拆分成这样的事情,也许:
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()
推荐阅读
- javascript - 蚂蚁设计风格
- authorize.net - Authorize.net : createcustomerprofilerequest : E00116 OTS 令牌访问冲突
- graphql - 有没有办法使用 graphql 订阅将数据与聚合一起获取?
- node.js - 当 Node.js API 出现故障时,是否可以阻止 nginx 响应?
- java - 如何在没有 GMT 的情况下使用 java.time.ZonedDateTime 和 format.DateTimeFormatter?
- java - TreeSet.lower() 方法在使用显式比较器构造函数时未返回所需的输出
- postgresql - 气流 2.1.3 使用 pgbouncer 解决 postgresql 问题
- xamarin.forms - Xamarin Android DisplayPromptAsync 无法禁止建议
- azure - 将 Function App 计划从消费升级到标准时出现意外错误。但只对某些人
- java - AWS lambda 有效,但网关无效