问题是编写一个程序,要求用户输入5个不同的学生和他们的标记。如果用户试图两次输入学生,程序应该检测到这个并要求他们输入一个唯一的学生姓名(和他们的标记)。
我的节目是..
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
name = raw_input("Enter a unique name: ")
mark = input("Enter the mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary
我的问题是如何循环else:代码如果用户一直输入相同的名称并标记?
答案 0 :(得分:1)
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
name = name.strip().lower() # store name in lower case, e.g. aamir and Aamir consider duplicate
if not dictionary.get(name):
mark = input("Enter your mark out of 100: ")
dictionary[name] = mark
count += 1
else:
print "please enter unique name"
print dictionary
aamir
和Aamir
都应视为重复Enter your mark
之前执行重复检查,以便为最终用户保存一个步骤答案 1 :(得分:1)
你混合input
和raw_input
,这是一件坏事。通常你在Python 2中使用raw_input
,在Python 3中使用input
。解决问题的快捷方法是:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = raw_input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
print("You already used that name, enter an unique name.")
print dictionary
答案 2 :(得分:0)
我认为你只需要这样做:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary