2013-02-02 79 views
0

我從一般的學習編程開始,到目前爲止,我最難理解的是如何以正確的方式離開我的循環,而不是使用'goto'。我聽說這是不好的做法。我知道Python沒有'goto'特性,但是如果它確實如此,這是我知道如何擺脫以下循環的唯一方式,無論它使用什麼語言。循環讓我困惑。另外,我不喜歡在編程時使用多少重複代碼,但我真的不知道如何避免它。可能通過使用函數,但我並不完全理解它們。如何擺脫Python中的循環(並縮短我的代碼)?

有人可以看看我的代碼,並告訴我如何使這項工作正常嗎?唯一的問題是最後,當它詢問用戶是否想要做出更多的改變時,當我輸入'y'時,它會進入無限循環,說'祝你有美好的一天'。我希望它回去並要求用戶改爲在選項A B和C之間進行選擇。其他一切似乎都在起作用。如果你還可以幫我縮短我的代碼,那會很棒。謝謝!

#Global variables 
more='y' 
#Enter your name 
name = raw_input("What is your first name? \n") 
##print('Your first name is ') + name 
lastName = raw_input("What is your last name? \n") 
##print('Your last name is ') + lastName 
##raw_input('Press enter to continue...') 
fullName = name + " " + lastName 
nameList = list(fullName) 
print('Your full name is ') + fullName + '. Would you like to \ 
edit your name? If yes, type "y" and if no type "n".\n' 
ans = raw_input() 
#Check if changing the name 
while more != 'n': 
    if ans == 'y': 
     ans=raw_input('Would you like to A) change a letter B) remove a \ 
letter or C) add a letter?\ 
\n\n(Note: For all changes write the position of the letter to be affected \ 
starting at 1 and going from left to right.)\n')  
#If yes, change the name  
     if ans=='A' or ans=='a': 
     #Change letter 
      change=input('Which letter would you like to change? ') 
      change -= 1 
      ans=raw_input('What would you like to change it to? ') 
      nameList[change]=ans 
      #Change the name 
      fullName = ''.join(nameList) 
      #Check if you want more changes 
      more=raw_input("Your name is now " + fullName + ".\n" + "Would you \ 
like to do anything else? Type 'y' if yes or 'n' if no. ")   
     elif ans=='B' or ans=='b': 
     #Remove letter 
      remove=input('Which letter would you like to remove? ') 
      remove -= 1 
      del nameList[remove] 
      #Change the name 
      fullName = ''.join(nameList) 
      #Check if you want more changes 
      more=raw_input("Your name is now " + fullName + ".\n" + "Would you \ 
like to do anything else? Type 'y' if yes or 'n' if no. ")   
     elif ans=='C' or ans=='c': 
     #Add letter 
      add=input('After which letter would you like to add one? ') 
      ans=raw_input('What letter would you like to add? ') 
      nameList.insert(add,ans) 
      #Change the name 
      fullName = ''.join(nameList) 
      #Check if you want more changes 
      more=raw_input("Your name is now " + fullName + ".\n" + "Would you \ 
like to do anything else? Type 'y' if yes or 'n' if no. ")    
#Otherwise say goodbye 
    else: 
     print('Have a nice day.') 

回答

0

我認爲這就是你想要的。

大的變化是變量more在循環中設置,緊跟在if塊之後,所以不需要重複該部分3次。 如果ans =「n」,程序立即退出(我認爲這就是你想要做的)。

from sys import exit 


more='y' 
name = raw_input("What is your first name? ") 
lastName = raw_input("What is your last name? ") 
fullName = '%s %s' % (name, lastName) 
nameList = list(fullName) 

print 'Your full name is %s. Would you like to edit your name? If yes, type "y" and if no type "n".\n' % fullName 
ans = raw_input() 
if ans == 'n': 
    print('Have a nice day.') 
    exit(0) 

while more != 'n': 

    ans=raw_input('Would you like to A) change a letter B) remove a \ 
letter or C) add a letter?\ 
\n\n(Note: For all changes write the position of the letter to be affected \ 
starting at 1 and going from left to right.)\n')  
    if ans in ('A','a'): 
     change=input('Which letter would you like to change? ') 
     change -= 1 
     ans=raw_input('What would you like to change it to? ') 
     nameList[change]=ans 
     fullName = ''.join(nameList) 
    elif ans in ('B','b'): 
     remove=input('Which letter would you like to remove? ') 
     remove -= 1 
     del nameList[remove] 
     fullName = ''.join(nameList) 
    elif ans in ('C','c'): 
     add=input('After which letter would you like to add one? ') 
     ans=raw_input('What letter would you like to add? ') 
     nameList.insert(add,ans) 
     fullName = ''.join(nameList) 

    more=raw_input("Your name is now " + fullName + ".\n" + "Would you \ 
like to do anything else? Type 'y' if yes or 'n' if no. ")   
+0

謝謝!這很有幫助。 –

1

我只是要去學習過程的其餘部分留給你和這樣說:看看break & continue,也許你會得到如何工作的事情出了一個主意。

+0

是的休息和繼續是有用的,但他最好學習如何把正確的條件放在while循環中。 – LtWorf

+0

@LWWorf誠然,我應該先看看他的代碼。但他應該能夠重新考慮他的計劃,並根據我給他的信息使其工作。 – David

+0

是的,這會使他產生糟糕的代碼而不是好的代碼。 – LtWorf

0

退出循環您可以break,或將循環在函數內部和return退出循環(和功能),或者,請確保您有可以在循環中被改變的退出條件當你準備退出時。你正在嘗試做第三個,它幾乎可以工作。代碼的問題在於條件if ans='y' ... else: print('Have a nice day')在循環內部,因爲它應該在循環外部,並且通過重用變量名稱ans來混淆事情。反正你可以按照如下用while條件結合起來是if條件:

name = raw_input("What is your first name? \n") 
last_name = raw_input("What is your last name? \n") 
full_name = name + " " + last_name 
edit = raw_input('Your full name is %s. Would you like to edit your name? \ 
If yes, type "y" and if no type "n" ' % full_name).lower() 

while edit != 'n': 
    option = raw_input("""Would you like to A) change a letter B) remove a \ 
letter or C) add a letter?\n\n(Note: For all changes write the position of the \ 
letter to be affected starting at 1 and going from left to right.)\n""").lower() 
    if option == 'a': 
     change = int(raw_input('Which letter would you like to change? ')) 
     to = raw_input('What would you like to change it to? ') 
     full_name = full_name[:change-1] + to + full_name[change:] 
    elif option == 'b': 
     remove = int(raw_input('Which letter would you like to remove? ')) 
     full_name = full_name[:remove-1] + full_name[remove:] 
    elif option == 'c': 
     after = int(raw_input('After which letter would you like to add one? ')) 
     letter = raw_input('What letter would you like to add? ') 
     full_name = full_name[:after] + letter + full_name[after:] 
    edit = raw_input("""Your name is now %s.\n Would you like to do \ 
anything else? Type "y" if yes or "n" if no. """ % full_name).lower() 
print "Have a nice day." 

沒有必要把字符串轉換成字符進行編輯的名單,所以我改變了這一點,但如果(例如)您將它用作練習來了解列表操作,然後您可能需要將其放回。

+0

謝謝,非常有幫助! –

0

將循環重構成函數是轉義嵌套循環的好方法。有時候,雖然我需要一個快速和骯髒的解決方案,並且這個例外是一個很好的工具。

try: 
    while True: 
    #some logic 
    while True: 
     #some logic 
     if condition: 
     raise Exception 
except Exception: 
    pass #or something else 

如果你找到你所需要的編碼後,跳出循環的,並且不希望重構爲可以擺脫使用這種方法深循環的功能。

+0

不錯,我到目前爲止還沒有在編程中使用'嘗試'。我真的需要更多地瞭解這一點。感謝您的迴應! –

+0

如果你決定走得更遠,我發現[this stack overflow answer](http://stackoverflow.com/a/730778/1961486)很有幫助。 – Octipi

+0

例外情況很慢,如果可以在正常情況下使用該情況,請使用條件。 – LtWorf