2016-09-29 72 views
0

我需要創建一個程序,它將輸入名稱和年齡的多個條目作爲輸入。然後,我希望它返回年齡值高於所有條目平均年齡的條目的名稱和年齡。 例如:創建一個向量,給定名稱和年齡的N個輸入python

input("Enter a name: ") Albert 
input("Enter an age: ") 16 

input("Enter a name: ") Robert 
input("Enter an age: ") 18 

input("Enter a name: ") Rose 
input("Enter an age: ") 20 

The average is = 18 
Rose at 20 is higher than the average. 

我該怎麼做?

回答

1
answers = {} 
# Use a flag to indicate that the questionnaire is active. 
questions_active = True 
while questions_active: 
# Ask for the person's name and response. 
    name = raw_input("\nEnter a name: ") 
    response = raw_input("Enter an age: ") 
# Store the response in the dictionary: 
    answers[name] = int(response) 
# Check if anyone else is going to take the questionnaire. 
    repeat = raw_input("Would you like to let another person respond? (yes/ no) ") 
    if repeat == 'no': 
     questions_active = False 

average_age = sum(answers.values())/float(len(answers)) 
print("The average is " + str(average_age)) 
# Questionnaire is complete. Show the results. 
for name, response in answers.items(): 
    if response > average_age: 
     print(name.title() + " at " + str(response) + " is higher than the average.") 

這個答案是基於從書「巨蟒速成班:一個基於項目的動手操作,程序設計入門」類似的例子https://www.nostarch.com/pythoncrashcourse

相關問題