0

I'm starting off with learning programming in general and so far the hardest thing for me to understand is how to get out of my loops the right way rather than using 'goto'. I hear it's bad practice. I know Python doesn't have the 'goto' feature but if it did, that's the only way I'd know how to get out of the following loop, no matter what language it was in. Loops confuse me. Also, I don't like how much repeated code I use when I program but I don't really know how to avoid it. Probably by using functions, but I don't understand them all that well.

Could someone please take a look at my code and instruct me how to make this work properly? The only issue is at the end when it asks if the user would like to make any more changes and when I enter 'y' it goes into an infinite loop saying 'Have a nice day'. I would like it to go back and ask the user to choose between options A B and C again instead. Everything else appears to be working. If you could also help me shorten my code that would be great. Thanks!

#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 Answers4

1

I'm just going to leave the rest of the learning process to you and say this: look into break &continue and maybe you'll get an idea of how to work things out.

David
  • 877
  • 1
  • 7
  • 18
  • Yes break and continue are useful, but he'd better learn how to put the correct condition in the while loop in the 1st place. – LtWorf Feb 02 '13 at 19:10
  • @LtWorf True, I probably should've looked through his code first. But he should be able to rethink his program and make it work given the information I gave him. – David Feb 02 '13 at 19:12
  • Yes, that will make him produce crappy code rather than good code. – LtWorf Feb 02 '13 at 19:14
  • @LtWorf Haha, he's only a beginner ;) – David Feb 02 '13 at 19:16
  • As important as the 'learning' process is, I don't really learn when I have to spend so much energy figuring it all out by googling for hours. All I want is a simple example of what needs to change with my code so I can look over it and see the differences. Still, thanks for the responses so far. – Spencer Evans Feb 02 '13 at 19:21
  • That's why I think he should begin learning the easier and correct way rather than the crappy,longer,slower way, which is usually what beginners take, so your answer should have given him the right answer, not the way to the crappy solution. – LtWorf Feb 02 '13 at 20:02
0

I think that's what you wanted.

The large change is that the variable more is set in the loop, right after the if block, so there is no need to repeat that part 3 times. Also if ans = "n", the program exits immediately (i presume that's what you wanted to do).

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. ")           
LtWorf
  • 7,286
  • 6
  • 31
  • 45
0

To exit a loop you can either break, or put the loop inside a function and return to exit the loop (and function), or, make sure you have an exit condition that can be altered within the loop when you are ready to exit. You are trying to do the third, and it's almost working. The problem with your code is that the condition if ans='y' ... else: print('Have a nice day') is inside the loop when it should be outside of it, and you are also confusing things by reusing the variable name ans. Anyway you can combine that if condition with the while condition as follows:

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

There is no need to turn the string into a list of characters to edit it, so I have altered that, but if (for example) you were using it as an exercise to learn about list manipulations then you may want to put it back.

Stuart
  • 9,597
  • 1
  • 21
  • 30
0

Refactoring a loop into a function is a nice way to escape nested loops. Sometimes though I need a quick and dirty solution and for this exceptions are a nice tool to have.

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

If you find you need to break out of a loop after coding and don't want to refactor into a function you can break out of deep loops using this method.

Octipi
  • 835
  • 7
  • 12
  • Nice, I haven't used 'try' at all in programming so far. I really need to learn more about this. Thanks for the response! – Spencer Evans Feb 03 '13 at 22:57
  • I found [this stack overflow answer](http://stackoverflow.com/a/730778/1961486) helpful, if you decide to go further. – Octipi Feb 03 '13 at 23:33
  • Exceptions are slow, if you can do that with a normal condition, use the condition. – LtWorf Feb 04 '13 at 07:48