Python回忆数据

时间:2013-12-07 02:46:21

标签: python

我正在尝试编写一个程序,允许我输入学生姓名,然后输入学生ID号码进行搜索。但是,我一直在遇到障碍,我不知道为什么。到目前为止,这是我的代码。

students={}


def add_student():
  #Lastname, Firstname
  name=raw_input("Enter Student's Name")
  #ID Number
  idnum=raw_input("Enter Student's ID Number")
  #D.O.B.
  bday=raw_input("Enter Student's Date of Birth")
  print "Student Added!" 



  students[idnum]={'name':name, 'bday':bday}


def delete_student():
  idnum=raw_input("delete which student:")
  if idnum in students:
     del students[idnum]

def find_student():
  print "Find" 
idnum=raw_input("Enter Student ID:")
  if [idnum] in students:
    print "Name:"[idnum]["name"]
    print "ID Number:"[idnum]["idnum"]
    print "Date of Birth:"[idnum]["bday"]


def show_student_record():
  idnum=raw_input("show which student's records?:")
  if idnum in students:
    print "Name:"[idnum]["name"]
    print "ID Number:"[idnum]["idnum"]
    print "Date of Birth:"[idnum]["bday"]



menu = {}
menu['1']="Add Student." 
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
menu['5']="Show Student Record"

while True: 
  options=menu.keys()
  options.sort()
  for entry in options: 
     print entry, menu[entry]

selection=raw_input("Please Select:") 
if selection =='1': 
    add_student()
elif selection == '2': 
    delete_student()
elif selection == '3':
    find_student() 
elif selection == '5':
    show_student_record()
elif selection == '4': 
    break
else: 
    print "Unknown Option Selected!" 
with open('Students', 'w') as saveFile:
  saveFile.write("Records" + "\n")

name=[]
idnum=[]
bday=[]


with open('Students', 'r') as inFile:
  for line in inFile:
    line = line.rstrip()


name.append(line[0]) 
idnum.append(line[1]) 
bday.append(line[2])

无论何时我尝试执行查找学生功能,我都会收到错误

Traceback (most recent call last):
  File "<stdin>", line 83, in <module>
  File "<stdin>", line 48, in find_student
  NameError: global name 'idnum' is not defined

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

def find_student():
    print "Find" 
    idnum=raw_input("Enter Student ID:")
    try:
        print "Name: " + students[idnum]["name"]
        print "ID Number: " + idnum
        print "Date of Birth: " + students[idnum]["bday"]
    except KeyError, ex:
        print ex.message + ' not found'

请注意:

  1. student[idnum]已取代[idnum],这就是您要说明要查看的词典的方式
  2. 关注python EAFP你试图找到密钥而不是询问它是否在那里

答案 1 :(得分:0)

尝试将[idnum]更改为idnum

def find_student():
print "Find" 
idnum=raw_input("Enter Student ID:")
if idnum in students:
    print "Name:"[idnum]["name"]
    print "ID Number:"[idnum]["idnum"]
    print "Date of Birth:"[idnum]["bday"]
else:
    print "Student not found"