2012-02-14 62 views
1

我有一項任務,指出...如何循環這個python腳本?

創建一個條件循環,它會要求用戶輸入兩個數字。應該添加數字並顯示總和。循環還應詢問用戶他或她是否希望再次執行該操作。如果是這樣,循環應該重複,否則循環應該終止。

這是我想出了...

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 2012-02-14 11:37:48

+1

看一下這個例子:http://wiki.python.org/moin/WhileLoop – ezdazuzena 2012-02-14 11:38:17

回答

4

您已將循環放置在錯誤的位置。需要做這樣的事情:

y = 'y' 

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

首先,y的值是'y',所以它會進入循環。第一次輸入後,提示用戶再次輸入y。如果他們輸入'y​​',那麼循環將再次執行,否則它將終止。

另一種方法是做一個無限循環,如果輸入'y'以外的任何東西就會中斷。這樣

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

東西,你需要把該while y=='y'在腳本的開始。

即使我不會把y這可能是要麼'n''y'
實例變量:

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'的東西。