2017-01-06 17 views
-4

申し訳ありませんが、これは複雑ではないようですが、私はPythonを初めて使用しています。辞書を使って条件を作成するにはどうすればいいですか?

子供のスコアが100以上であれば、プレゼントは8点あります。子供のスコアが50〜100の場合は5つのプレゼントを、子供のスコアが50未満の場合は2つのプレゼントを得る。

辞書を使用してユーザーの入力が正しいかどうかを確認するにはどうすればよいですか?尋ねた質問に関連

presents=[] 
People={"Dan":22, 
     "Matt":54, 
     "Harry":78, 
     "Bob":91} 

def displayMenu(): 
    print("1. Add presents") 
    print("2. Quit") 
    choice = int(input("Enter your choice : ")) 
    while 2< choice or choice< 1: 
     choice = int(input("Invalid. Re-enter your choice: ")) 
    return choice 

def addpresents(): 
    name= input('Enter child for their score: ') 
    if name == "matt".title(): 
     print(People["Matt"]) 
    if name == "dan".title(): 
     print(People["Dan"]) 
    if name == "harry".title(): 
     print(People["Harry"]) 
    if name == "bob".title(): 
     print(People["Bob"]) 
    present=input('Enter number of presents you would like to add: ') 
    if present 
     #This is where I got stuck 

option = displayMenu() 

while option != 3: 
    if option == 1: 
     addpresents() 
    elif option == 2: 
     print("Program terminating") 

option = displayMenu() 
+3

を質問は何ですか? – fedepad

+0

「プレゼント」とは何ですか?子供に贈りたいプレゼントの数ですか?もしそうなら、それを与えるためにプレゼントの量をあらかじめ定義しておけばそれはなぜですか? –

+0

あなたが求めていることはあまり明確ではありません。あなたの質問をもう一度見て、あなたが問題を抱えていることを正確に再確認しようとしてください。 –

答えて

0

:それが最初のような彼らのスコア表示していました

子供のスコアは、彼らが8つのプレゼントを取得する必要があります100以上の場合に、子供のスコアが50〜100の場合は5つのプレゼントを、子供のスコアが50未満の場合は2つのプレゼントを得る。

キーがスコアのブール条件である辞書を作成します。しかし、scoreがそのキーに使われているので、毎回辞書を再作成しなければならず、スコアは各サイクルごとに異なる可能性があります。

>>> score = 3 
>>> presents = {score < 50: 2, 
...    50 <= score < 100: 5, 
...    score >= 100: 8 
...    }[True] 
>>> presents 
2 
>>> # and keep re-doing the 3 statements for each score. 

実際には、各辞書のキーは、これまでTrueに評価するだけでTrueまたはFalseになります。したがって、キーの値を取得すると、Trueが表示されます。

def get_presents(score): 
    return {score < 50: 2, 
      50 <= score < 100: 5, 
      score >= 100: 8 
      }[True] 

そしてそうのようにそれを使用します:のは、かなり遠く意図から思われること、あなたが使用したコードのよう

>>> get_presents(25) 
2 
>>> get_presents(50) 
5 
>>> get_presents(100) 
8 
>>> 

関数にそれを置く

は次のように、より理にかなっています質問に。

また、あなたがキーとしてint(score/50)行うことができます:

>>> present_dict = {1: 2, 
...     2: 5, 
...     3: 8 
...     } 
>>> 
>>> score = 500 
>>> present_dict[min(int(score/50) + 1, 3)] # needed to not go over 3 
8 
>>> score = 25 
>>> present_dict[min(int(score/50) + 1, 3)] # the +1 needed since it's int div 
2 
>>> # or put the expression above in the `get_presents` function and return that 
関連する問題