2014-01-19 60 views
1

問題是編寫一個程序,要求用戶輸入5個不同的學生及其標記中的100個。如果用戶試圖輸入一個學生兩次,程序應檢測到這一點,要求他們輸入一個獨特的學生姓名(和他們的標誌)。Python:要求用戶輸入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 

我的問題是你怎麼循環的東西:代碼,如果用戶仍能保持輸入相同的名稱和標誌?

+0

一般性意見:如果測試如果「mike」在字典中,「Mike」在字典中將不會返回true。您應該存儲名稱的較低/大寫版本,然後匹配較低/大寫輸入以查看它是否已經存在。 – Dyrborg

回答

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 
  • 店鋪名稱以小寫使aamirAamir都應該考慮複製
  • 重複檢查應早於一步Enter your mark進行保存終端用戶一步
1

你混合inputraw_input,這是一件壞事。通常你在Python 2和input在Python 3使用raw_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 
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 
相關問題