1

プログラムのオン/オフスイッチを作成しようとしています: (###私が話していることについては、の後に参照してください)

while 1:
    str = raw_input("insert your word: ")
    n = input("insert your scalar: ")
    def string_times(str, n):
        return n * str
    print string_times(str, n)

    ###
    def switch(on,off):
        raw_input("On or off? ")
        if switch == "on":
            continue
        if switch == "off":
            break
    switch(on,off)

continue not in loop エラーが発生します。基本的には、プログラムが一度実行された後にオンまたはオフのスイッチを作成したいと考えています。何を修正すればよいですか?

4

1 に答える 1

11

ネストされた関数ではbreakandを使用できません。continue代わりに関数の戻り値を使用します。

def switch():
    resp = raw_input("On or off? ")
    return resp == "on":

while True:
    # other code

    if not switch():
        break

ループ内で関数を定義する意味はほとんどないことに注意してください。関数オブジェクトの作成にはある程度のパフォーマンスが必要なので (少量ではありますが)、ループの前に定義してください。

関数には引数はswitch()必要ありません (まったく使用しませんでした)。また、continueも必要ありません。ループから抜け出さなかった場合は、最後に到達したときに上から続きます。

ループ内の残りのコードをスキップcontinueして、ループを最初から開始する場合にのみ必要です。

count = 0
while True:
    count += 1
    print count
    if loop % 2 == 0:
        continue

    print 'We did not continue and came here instead.'

    if count >= 3:
        break

    print 'We did not break out of the loop.'
于 2013-01-14T18:28:14.367 に答える