2012-02-14 2 views
1

私は状態が割り当てられています...このpythonスクリプトをループする方法は?

ユーザに2つの数字の入力を求める条件ループを作成します。数字を追加し、合計を表示する必要があります。ループはまた、ユーザに、操作を再度実行したいかどうかを尋ねるべきである。そうであれば、ループを繰り返す必要があります。そうでなければ、ループは終了します。

これがします私はあなたがこれを実行すると、プログラムの最初の部分が動作します

n1=input('Please enter your first number: ') 
print "You have entered the number ",n1,"" 
n2=input('Pleae enter your second number: ') 
print "You have entered the number ",n2,"" 
total=n1+n2 
print "I will now add your numbers together." 
print "The result is:",total 

y = raw_input('Would you like to run the program again? y=yes n=no') 
print'The program will now terminate.' 

y='y' 
while y=='y': 
print 'The program will start over.' 

...が出ているが、それを再度実行するかを尋ねたときに、それが継続的に「プログラムの状態になるものです始める。

ユーザーはプログラムを開始したいかどうかを入力することができますが、これをループするようにどのように言いますか?

+0

ループコード全体を教えてください。 – shenshei

+1

この例を見てください:http://wiki.python.org/moin/WhileLoop – ezdazuzena

答えて

4

ループを間違った場所に配置しました。

y = 'y' 

while y == 'y': 
    # take input, print sum 
    # prompt here, take input for y 

最初にyの値が 'y'であるため、ループに入ります。最初の入力後、yを再度入力するようユーザーに指示します。 「y」と入力するとループが再び実行され、そうでない場合は終了します。

「y」以外が入力された場合、無限ループを作り、それを中断する方法もあります。あなたのスクリプトの先頭にそのwhile y=='y'を配置する必要があり、この

while True: 
    # take input, print sum 
    # prompt here, take input for y 
    # if y != 'y' then break 
1

ような何か。

def program(): 
    n1 = input('Please enter your first number: ') 
    print "You have entered the number ",n1,"" 
    n2 = input('Pleae enter your second number: ') 
    print "You have entered the number ",n2,"" 
    total = n1+n2 
    print "I will now add your numbers together." 
    print "The result is:",total 


flag = True 
while flag: 
    program() 
    flag = raw_input('Would you like to run the program again? [y/n]') == 'y' 

print "The program will now terminate." 

あれば、このようにあなたがプログラムを終了することを指摘しておかなければにもかかわらず:私はy'n''y'
いずれかの例かもしれない変数を呼び出すことはありませんにもかかわらず

ユーザーは'y'でないものを挿入します。

関連する問題