0

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

4 回答 4

1

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

于 2013-02-02T19:10:08.743 回答
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. ")           
于 2013-02-02T20:20:54.047 回答
0

要退出循环,您可以break,或者将循环放入函数中并return退出循环(和函数),或者,确保在准备退出时可以在循环内更改退​​出条件。你正在尝试做第三个,它几乎可以工作了。您的代码的问题在于,条件if ans='y' ... else: print('Have a nice day')应该在循环之外,而条件却在循环内部,并且您还通过重用变量 name 来混淆事情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."

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

于 2013-02-02T21:09:18.340 回答
0

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

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

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

于 2013-02-02T23:42:11.903 回答