我开始学习一般的编程,到目前为止,我最难理解的是如何以正确的方式摆脱我的循环,而不是使用“goto”。我听说这是不好的做法。我知道 Python 没有“goto”功能,但如果有,这是我知道如何摆脱以下循环的唯一方法,无论它使用什么语言。循环让我感到困惑。另外,我不喜欢在编程时使用多少重复代码,但我真的不知道如何避免它。可能是通过使用函数,但我不太了解它们。
有人可以看看我的代码并指导我如何使其正常工作吗?唯一的问题是最后当它询问用户是否愿意进行更多更改时,当我输入“y”时,它会进入一个无限循环,说“祝你有美好的一天”。我希望它返回并要求用户再次在选项 AB 和 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.')