1

Pythonの辞書について質問です。ユーザーに 2 つのオプションが表示される辞書を作成したいと思います。辞書を更新するか、辞書をクリアします。最初に私のコードをお見せしましょう:

def myStuff():
    food = {'Apple': 0, 'Banana': 0, 'Grapes': 0}
    choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
    if choice == str(1):
        apple = int(raw_input('How many apples do you want to add?\n>>'))
        banana = int(raw_input('How many bananas do you want to add?\n>>'))
        grapes = int(raw_input('How many grapes do you want to add?\n>>'))
        print 'Updating...'
        food['Apple'] = apple
        food['Banana'] = banana
        food['Grapes'] = grapes
        print  food
    elif choice == str(2):
        food['Apple'] = 0
        food['Banana'] = 0
        food['Grapes'] = 0
        print food
    else:
        return False

myStuff()

ここに私が追加したいものがあります:

1. ユーザーが辞書を更新し続ける機能 (つまり、誰かが 10 個のリンゴを入力すると、辞書は 10 個のリンゴを格納し、ユーザーは辞書を更新するために入力したいリンゴの数を入力するように再度求められます) . これにループを実装する方法がよくわかりません。

2、ユーザーが辞書を更新した後に辞書をクリアする機能。例: 誰かが 10 個のリンゴを入力した場合、ループはユーザーに辞書をクリアするかどうかを再度尋ねます。

誰かがお金を預けて、口座にお金が残っていない場合に口座を清算する銀行のようなものです。

4

4 に答える 4

0

あなたはこのようにそれを行うことができます:

"""
in each loop check the fruit number to see if it is 0 or not.if it
is 0, then this means that you don't want to add fruit from the current 
type and skips to the nextFruit.Focus on the code and you realize the other parts.
"""    

import string

def myStuff():
    food = {'Apples': 0, 'Bananas': 0, 'Grapes': 0}
    choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
    fruit = 0
    nextFruit = 'Apples'
    while True:
        if choice == str(1):
            fruit = int(raw_input('How many ' + str.lower(nextFruit) + ' do you want to add?\n>>'))
            if fruit == 0 and nextFruit == 'Apples':
                nextFruit = 'Bananas'
                continue
            elif fruit == 0 and nextFruit == 'Bananas':
                nextFruit = 'Grapes'
                continue
            elif fruit == 0 and nextFruit == 'Grapes':
                print 'Updating...'
                print  food
                choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
            else:
                food[nextFruit] += fruit
        elif choice == str(2):
            food['Apples'] = 0
            food['Bananas'] = 0
            food['Grapes'] = 0
            print 'Updating...'
            print  food
            choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
        else:
            print "You've entered a wrong number....try again please:"
            print
            choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
于 2012-12-19T00:48:49.797 に答える
0

あなたがしていることでは、独自のクラスを作成する方が良いかもしれません。また、実行したいさまざまなアクションすべてに対して、さまざまな機能が必要です。すなわち。更新、クリア、追加

class Fruit:
    Apple = 0
    Banana = 0
    Grape = 0

    def __repr__(self):
         return "You have {self.Apple} apples, {self.Banana} bananas, and {self.Grape} grapes".format(**locals())

    def update(self):
       while 1:
         choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
         if (int(choice) == 1):
            self.Add()
         elif (int(choice) == 2):
            self.Clear()
         else:
             print "Input not valid"

    def Add(self):
       self.Apple += int(raw_input('How many apples do you want to add?\n>>'))
       self.Banana += int(raw_input('How many bananas do you want to add?\n>>'))
       self.Grape += int(raw_input('How many grapes do you want to add?\n>>'))
       print self

    def Clear(self):
       self.Apple = 0
       self.Banana = 0
       self.Grape = 0
       print self

if __name__ == "__main__":
    fruit = Fruit()
    fruit.update()         

また、間違った入力が使用された場合にプログラムがクラッシュしないように、tryandステートメントを使用することも検討する必要があります。exceptまた、プログラムを終了するために終了コマンドを追加する必要があります。そうしないと、これは永遠にループします。例えば。ユーザー入力が「exit」の場合は、条件付きでそれとbreak.

于 2012-12-21T20:07:29.847 に答える
0
  1. ループで更新するには、次のようなものを試してください。

    for key in food:
        food[key] += int(raw_input('How many %s do you want to add?> ' % key) or 0)
    
  2. 値をゼロに設定することで、すでに辞書をクリアしています。

于 2012-12-18T23:08:17.877 に答える
0

私の理解が正しければ、この質問を繰り返し続けたいですか?その場合、while True:繰り返したいコードのブロックを配置してインデントするだけで、永遠にループします。raw_inputおそらく、 ( inputPython 3 だけで) から - の直後まで保持したいでしょう。elifまたは、foodグローバル変数を作成する場合 (呼び出されるたびに 0 に再初期化されないようにするためmyStuff())、単に実行できます。 :

while True:
  myStuff()
于 2012-12-18T23:44:55.710 に答える