如何在Python中摆脱循环(并缩短代码)?

如何在Python中摆脱循环(并缩短代码)?,python,loops,goto,Python,Loops,Goto,我从学习编程开始,到目前为止,我最难理解的是如何以正确的方式摆脱循环,而不是使用“goto”。我听说这是个坏习惯。我知道Python没有“goto”特性,但如果它有,那是我知道如何摆脱以下循环的唯一方法,不管它使用的是什么语言。循环让我困惑。此外,我不喜欢在编程时使用多少重复代码,但我真的不知道如何避免。可能是通过使用函数,但我并不完全理解它们 有人可以看看我的代码,并告诉我如何使这项工作正常吗?唯一的问题是在最后,当它询问用户是否愿意做更多的更改时,当我输入“y”时,它进入一个无限循环,说“祝

我从学习编程开始,到目前为止,我最难理解的是如何以正确的方式摆脱循环,而不是使用“goto”。我听说这是个坏习惯。我知道Python没有“goto”特性,但如果它有,那是我知道如何摆脱以下循环的唯一方法,不管它使用的是什么语言。循环让我困惑。此外,我不喜欢在编程时使用多少重复代码,但我真的不知道如何避免。可能是通过使用函数,但我并不完全理解它们

有人可以看看我的代码,并告诉我如何使这项工作正常吗?唯一的问题是在最后,当它询问用户是否愿意做更多的更改时,当我输入“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.')

我将把剩下的学习过程留给你,我想说的是:看看
break
&
continue
,也许你会知道如何解决问题。

我想这就是你想要的

最大的变化是在循环中设置了变量more,就在if块之后,因此无需重复该部分3次。 另外,如果ans=“n”,程序会立即退出(我想这是您想要做的)


要退出循环,您可以
中断
,或者将循环放入函数中,然后
返回
退出循环(和函数),或者,确保您有一个退出条件,当您准备退出时,可以在循环中更改该退出条件。你正在尝试做第三件事,而且几乎成功了。代码的问题在于,如果ans='y'。。。否则:print('Have anice day')在循环内部,而它本应在循环外部,并且重复使用变量名
ans
也会使事情变得混乱。无论如何,您可以将
if
条件与
while
条件组合,如下所示:

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."

无需将字符串转换为字符列表进行编辑,因此我对其进行了修改,但如果(例如)您将其用作练习来学习列表操作,则可能需要将其放回。

将循环重构为函数是一种逃避嵌套循环的好方法。虽然有时我需要一个快速而肮脏的解决方案,但对于这种例外情况,这是一个很好的工具

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

如果您发现编码后需要中断循环,并且不想重构为函数,则可以使用此方法中断深循环。

是的,中断和继续很有用,但他最好首先学习如何在while循环中设置正确的条件。@LtWorf如果是,我可能应该先查看他的代码。但他应该能够重新思考他的程序,并根据我给他的信息使其工作。是的,这将使他产生糟糕的代码而不是好代码。@LtWorf哈哈,他只是个初学者;)与“学习”过程一样重要的是,当我不得不花这么多精力通过谷歌搜索数小时来弄清楚这一切时,我并没有真正学会。我想要的只是一个简单的例子,说明我的代码需要更改什么,这样我就可以查看它并看到差异。不过,还是要感谢大家的回复。很好,到目前为止,我还没有在编程中使用“try”。我真的需要更多地了解这一点。谢谢你的回复!如果你决定更进一步,我发现这很有帮助。异常是缓慢的,如果你能在正常条件下做到这一点,请使用该条件。
try:
  while True:
    #some logic
    while True:
      #some logic
      if condition:
        raise Exception
except Exception:
  pass #or something else