1

whileユーザーが「exit」と入力するまで、以下のプログラムを続行する非常に単純なループ ステートメントは何でしょうか?

例えば、

while response = (!'exit')
    continue file
else
    break
    print ('Thank you, good bye!')
#I know this is completely wrong, but it's a try!

これまでの私のファイル:

#!/usr/bin/python
friends = {'John' : {'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']},
    'Harry' : {'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']}}
response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()
try:
    print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])
except KeyError:
    print "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "
4

3 に答える 3

4

continue引数を必要としないキーワードです。現在のループに、次の繰り返しにすぐに続行するように指示するだけです。whileandforループ内で使用できます。

次に、コードをwhileループ内に配置する必要があります。ループは、条件が満たされるまで続行されます。条件構文が正しくありません。読む必要がありますwhile response != 'exit':。条件を使用しているため、continueステートメントは必要ありません。値が ではない限り、設計上継続します"exit"

構造は次のようになります。

response = ''
# this will loop until response is not "exit"
while response != 'exit':
    response = raw_input("foo")

を利用したい場合はcontinue、応答に対して他のさまざまな操作を行う場合に使用される可能性があり、早期に停止して再試行する必要がある場合があります。キーワードは、ループに作用する同様のbreak方法ですが、代わりに、ループをすぐに完全に終了する必要があることを示しています。契約を破るその他の条件がある可能性があります。

while response != 'exit':
    response = raw_input("foo")

    # make various checks on the response value
    # obviously "exit" is less than 10 chars, but these
    # are just arbitrary examples
    if len(response) < 10:
        print "Must be greater than 10 characters!"
        continue  # this will try again 

    # otherwise
    # do more stuff here
    if response.isdigit():
        print "I hate numbers! Unacceptable! You are done."
        break
于 2012-05-05T01:44:18.397 に答える
3
#!/usr/bin/python
friends = {
    'John' : {
        'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']
    },
    'Harry' : {
        'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']
    }
}

def main():
    while True:
        res = raw_input("Please enter search criteria, or type 'exit' to exit the program: ")
        if res=="exit":
            break
        else:
            name,val = res.split()
            if name not in friends:
                print("I don't know anyone called {}".format(name))
            elif val not in friends[name]:
                print("{} doesn't have a {}".format(name, val))
            else:
                print("{}'s {} is {}".format(name, val, friends[name][val]))

if __name__=="__main__":
    main()
于 2012-05-05T02:01:31.367 に答える
3

while ループは、設定した条件が false になるまで続きます。したがって、コードはほとんどこのループ内にある必要があります。完了すると、ユーザーが「exit」と入力したことがわかり、エラー メッセージを出力できます。

#!/usr/bin/python
friends = {'John' : {'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']},
    'Harry' : {'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']}}

response = ['']
error_message = "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "

while response[0] != 'exit':
    response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()
    try:
        print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])
    except KeyError:
        print error_message
    except IndexError:
        print error_message

print ('Thank you, good bye!')

このコードはあなたが望むものへの出発点ですが、まだいくつかのバグがあります。ユーザーが「exit」を入力したときにエラーメッセージが出力されないように再構築できるかどうかを確認してください。

于 2012-05-05T01:37:54.153 に答える