我正在尝试在python 3中创建一个程序,它将要求用户输入学生姓名(姓名)和他/她的ID号(ID)一次性用逗号分隔。然后以下列格式显示所有字典值,例如: 姓名:John ID:123 姓名:Mary ID:234 姓名:Eve ID:345 程序将永远运行,除非用户输入q退出
到目前为止,我设法创建了以下内容:
addName = raw_input("New Name:")
addid = raw_input("ID:")
dictionary = {}
dictionary[addName] = addid
print('Name: ' + addName + ' ID: ' + addid)
我希望程序继续运行,除非用户输入q退出。如何在一行中输入,以便用户输入其名称,然后输入其ID,用逗号分隔?同时打印字典包含的所有名称和ID。
答案 0 :(得分:0)
几个月来,我对自己编码很陌生,但这里有一些我可能会有所帮助的东西。我在整个代码中使用了很多注释,因此您知道我正在尝试做什么。
# Initilize values
i = 0
StuName = None
ID = None
students = {}
# Loop structure that says "While this is true, do this"
while 1:
i+=1
student=input('Enter student name and ID or q to exit: ')
# if the user enters 'q' break out of the loop
if student=='q':
break
else:
# This line takes "John,123" and splits it on the comma into "John" and "123".
# It stores these under the variables StuName and ID
StuName, ID = student.split(',')
# This line updates the "students" dictionary with whatever value "StuName" is and "ID" is
students.update({StuName:ID})
# This line iterates through the "students" dictionary and prints according to how we say
for StuName, ID in students.items():
#This line is mostly fancy formatting. the \t is a tab, {} is where your variables (StuName, ID) will go
print ('Name: {}\tID: {}'.format(StuName, ID))