【问题标题】:Fixing a While loop in a pig latin translator修复猪拉丁语翻译器中的 While 循环
【发布时间】:2015-10-02 09:55:03
【问题描述】:

我正在开发一个猪拉丁语翻译程序:

  1. 提示用户输入单词。
  2. 如果单词以元音开头,则在单词末尾附加“way”。
  3. 如果单词以辅音开头,则删除单词开头的所有辅音,并将它们附加到单词的末尾。然后,将“ay”附加到单词的末尾。
  4. 当用户输入“quit”(大小写字母的任意组合,例如“QUIT”、“Quit”或“qUIt”)时停止

我的程序很好地满足了 1-3,但我似乎无法弄清楚如何不断提示用户输入单词,除非他们输入某种形式的“退出”。我知道我需要使用 while 语句,但这是我想出的最好的:

while True:

VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")

statement = input("Please enter a word: ")
statementL = statement.lower()

if statementL == "quit":
    print ("Exiting program")
    break


def find_vowel(word):
   for i in range(len(word)):
     if word[i] in VOWELS:
        return i
   return -1

words =  statement.split()
count = 0

for word in words:
   vowel = find_vowel(word)
# No vowels found
   if(vowel == -1):
      print (word)
# A vowel is the first letter
   elif(vowel == 0):
    print (word + "way")
   else:
# A consonant is first
    print (word[vowel:] + word[:vowel] + "ay")

我当前的 while 循环不断提示用户输入一个单词,但没有翻译它,当我尝试将退出程序块移动到底部时出现错误。有什么建议么?提前致谢。

【问题讨论】:

  • 我认为你的缩进是关闭的
  • 是的,就是这样。谢谢

标签: python python-3.x while-loop


【解决方案1】:

我不太确定问题是什么。我复制了你的代码字符,它运行正确。可能存在的唯一问题是您认为在 while 循环中的代码可能不在。检查你的缩进。这是我运行的代码:

while True:

    VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")

    statement = input("Please enter a word: ")
    statementL = statement.lower()

    if statementL == "quit":
        print ("Exiting program")
        break


    def find_vowel(word):
       for i in range(len(word)):
         if word[i] in VOWELS:
            return i
       return -1

    words =  statement.split()
    count = 0

    for word in words:
       vowel = find_vowel(word)
       # No vowels found
       if(vowel == -1):
          print (word)
       # A vowel is the first letter
       elif(vowel == 0):
          print (word + "way")
       else:
          # A consonant is first
          print (word[vowel:] + word[:vowel] + "ay")  

【讨论】:

  • 是的,就是缩进。我觉得自己像个白痴哈哈。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多