0

私は一般的なプログラミングの学習から始めていますが、これまでのところ、理解するのが最も難しいのは、「goto」を使用するのではなく、正しい方法でループから抜け出す方法です。悪い習慣だと聞きました。Pythonに「goto」機能がないことは知っていますが、ある場合は、どの言語を使用していても、次のループから抜け出す方法を知る唯一の方法です。ループは私を混乱させます。また、プログラムするときにどれだけ繰り返されるコードを使用するかは好きではありませんが、それを回避する方法はよくわかりません。関数を使っているのかもしれませんが、よくわかりません。

誰かが私のコードを見て、これを正しく機能させる方法を教えてもらえますか?唯一の問題は、ユーザーがこれ以上変更を加えたいかどうかを尋ねられたときです。「y」と入力すると、「Haveaniceday」という無限ループに入ります。戻って、代わりにオプション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

ループを終了するにはbreak、またはループを関数内に配置しreturnてループ(および関数)を終了するか、終了する準備ができたときにループ内で変更できる終了条件があることを確認します。あなたは3番目をやろうとしています、そしてそれはほとんど働いています。コードの問題は、条件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."

文字列を編集するために文字のリストに変換する必要はないので、それを変更しましたが、たとえば、リストの操作について学習するための演習として文字列を使用している場合は、元に戻すことをお勧めします。

于 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 に答える
0

それがあなたが望んでいたことだと思います。

大きな変更点は、if ブロックの直後のループ内で変数 more が設定されているため、その部分を 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 に答える