我從一般的學習編程開始,到目前爲止,我最難理解的是如何以正確的方式離開我的循環,而不是使用'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.')
謝謝!這很有幫助。 –