for循环打印“找不到学生”超过1次

时间:2019-07-10 10:33:00

标签: python json

我有一个学生管理程序,我使用for循环在列表内的字典中查找,因此我有ifelif条件来搜索学生数据。但是,它也提供3或4个elif条件的输出。我希望如果程序找不到学生数据,则只打印一次“找不到学生”,如果我有学生数据,则仅if子句不应运行elif

    import json
    while True:
            student={}
            with open('Data file for student management system.json','r') as f:
                    students=json.load(f)
            print('''\n"1 or add" to Add Student''')
            print('''"2 or edit" to Edit Student''')
            print('''"3 or delete" to Delete Student''')
            print('''"4 or search" to Search Student''')
            print('''"5 or display" to Display all Students''')
            while True:
                    try:
                            option=str(input('''\nPlease enter any option given above:'''))
                            if option not in ['1','2','3','4','5','add','delete','edit','search','display']:
                                    print('''\n"Please select a correct options"''')
                            else:
                                    break
                    except ValueError:
                            print('''"Please enter a correct number only"''')
            if option in ['1','add']:
                    student["Name"] = input ("\nStudent's Name:").title()
                    student["Father Name"] = input ("Father's Name:").title()
                    student["Age"] = input ("Student's Age:")
                    student["Address"] = input ("Address:").title()
                    students.append(student)
                    with open('Data file for student management system.json','w') as f:
                            json.dump(students,f)
                    student={}
                    print('''\n"Addition Successful"''')
            elif option in ['2','edit']:
                    Name=input("\nPlease type name:").title()
                    new_name=input("\nWhat is new name:").title()
                    for s in list(students):
                            for d in s:
                                    if s['Name']==Name:
                                            s['Name']=new_name
                                            print('''\n"Edit Successful"''')
                                            with open('Data file for student management system.json','w') as f:
                                                    json.dump(students,f)
                                    elif s['Name']!=Name:
                                            print('''\n"Student not found"''')
                                            break
            elif option in ['3','delete']: 
                    del_name=input("\nPlease type name of student you want to delete:").title()
                    for s in list(students):
                            for d in s:
                                    if s['Name']==del_name:
                                            ind=students.index(s)
                                            while True:
                                                    sure=input('\nAre you sure you want to delete?\n\nYes or No:').lower()
                                                    if sure in ['yes','y']:
                                                            del students[ind]
                                                            print('''\n"Deletion Successful"''')
                                                            with open('Data file for student management system.json','w') as f:
                                                                    json.dump(students,f)
                                                            break
                                                    elif sure in ['no','n']:
                                                            print("\nStudent data not deleted")
                                                            break
                                                    else:
                                                            print('''"\nPlease enter a coorect option"''')
                                            break
                                    elif s['Name']!=del_name:
                                            print('''\n"Student not found"''')
                                            break
            elif option in ['4','search']:
                    s_name=input("\nEnter name of student:").title()
                    for d in students:
                            for k,v in d.items():                
                                    if d['Name']==s_name:
                                            print(" ____________________________________________________________________________________________________________________________")
                                            print("|          |                                |                                 |                                              |")
                                            print("|   S-No   |              Name              |            Father Name          |                     Address                  |")
                                            print("|__________|________________________________|_________________________________|______________________________________________|")
                                            print(f"|          |{d['Name']: <32}|{d['Father Name']: <33}|{d['Address']: <46}|")
                                            print("|__________|________________________________|_________________________________|______________________________________________|")
                                            break
                                    elif d['Name']!=s_name:
                                            print('''\n"Student not found"''')
                                            break
            elif option in ['5','display']:
                    print(" ____________________________________________________________________________________________________________________________")
                    print("|          |                                |                                 |                                              |")
                    print("|   S-No   |              Name              |            Father Name          |                     Address                  |")
                    print("|__________|________________________________|_________________________________|______________________________________________|")
                    for s in students:
                            for k,v in s.items():
                                    pass

                            print(f"|          |{s['Name']: <32}|{s['Father Name']: <33}|{s['Address']: <46}|")
                            print("|__________|________________________________|_________________________________|______________________________________________|")
            while True:
                    Repeat=input("\nDo you want to repeat?\n\nYes or No:")
                    Repeat=Repeat.lower()
                    if Repeat not in ["yes","y","no","n"]:
                            print("\nPlease select correct option")
                    else:
                            break
            if Repeat in ["yes","y"]:
                    continue
            else:
                    if Repeat in ["no","n"]:
                            print("\n-----Thank you for using-----")
                            input()
                            break

json文件

    [{"GR#": 1, "Name": "Daniyals", "Age": 12, "Father Name": "Ajaz", "Address": "Flat-123, Block ABC"}, {"GR#": 2, "Name": "Shahrukh Khan", "Age": 9, "Father Name": "Ajeeb Khan", "Address": "Khan Mansion"}, {"Name": "Waseem Munir", "Father Name": "Sdasd", "Age": "asdasdas", "Address": "Asdasdas"}, {"Name": "Saad", "Father Name": "Asdsadas", "Age": "asdasdas", "Address": "Asdas"}, {"Name": "Sdasd", "Father Name": "Adsadas", "Age": "dasdas", "Address": "Dasdas"}]

1 个答案:

答案 0 :(得分:0)

我建议使用pandas dataFrame它将使它变得如此简单。

import pandas as pd
df = pd.DataFrame(
    {'Name': ['a','b','c','d'], #Your name list here
      'Fathers Name': np.zeros(4), #Your data here
     'Address': np.zeros(4), #Your data here and add more columns 
    })

s_name=input("\nEnter name of student:").title()

for i in range(len(df)):
    if df['Name'][i] == s_name:
        print(df.loc[i])