【问题标题】:How to get out of my loop in Python (and shorten my code)?如何摆脱我在 Python 中的循环(并缩短我的代码)?
【发布时间】:2013-02-02 19:04:54
【问题描述】:

我开始学习一般的编程,到目前为止,我最难理解的是如何以正确的方式摆脱我的循环,而不是使用“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.')

【问题讨论】:

    标签: python loops goto


    【解决方案1】:

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

    【讨论】:

    • 是的 break 和 continue 很有用,但他最好先学习如何将正确的条件放在 while 循环中。
    • @LtWorf 没错,我可能应该先查看他的代码。但根据我提供的信息,他应该能够重新考虑他的程序并使其发挥作用。
    • 是的,这会让他产生蹩脚的代码而不是好的代码。
    • @LtWorf 哈哈,他只是个初学者;)
    • 尽管“学习”过程很重要,但当我不得不花费大量精力通过谷歌搜索数小时来弄清楚这一切时,我并没有真正学习。我想要的只是一个简单的例子,说明我的代码需要改变什么,这样我就可以查看它并查看差异。不过,感谢您迄今为止的回复。
    【解决方案2】:

    我想这就是你想要的。

    最大的变化是变量 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. ")           
    

    【讨论】:

      【解决方案3】:

      要退出循环,您可以break,或将循环放在函数中,然后return 退出循环(和函数),或者确保您有一个可以在循环内更改的退出条件当您准备退出时。你正在尝试做第三个,它几乎可以工作了。您的代码的问题在于条件if ans='y' ... else: print('Have a nice 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."
      

      无需将字符串转换为字符列表即可对其进行编辑,因此我已对其进行了更改,但如果(例如)您将其用作学习列表操作的练习,那么您可能需要输入它回来了。

      【讨论】:

        【解决方案4】:

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

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

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

        【讨论】:

        • 很好,到目前为止我还没有在编程中使用过'try'。我真的需要更多地了解这一点。感谢您的回复!
        • 我发现 this stack overflow answer 很有帮助,如果您决定更进一步。
        • 异常很慢,如果你可以在正常条件下做到这一点,请使用条件。
        猜你喜欢
        • 2022-12-02
        • 2018-11-30
        • 2019-12-16
        • 1970-01-01
        • 1970-01-01
        • 2019-01-15
        • 1970-01-01
        • 2014-09-05
        • 1970-01-01
        相关资源
        最近更新 更多