python中的循环和转换字符串

2024-09-28 17:26:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手,我很难理解如何询问用户是否想再次运行它

    def pigLatin(word):
     """
   Function that converts word into Pig Latin form
     """

  # Checking for starting letter as vowel
  if word[0] in ['a','e','i','o','u']:
   return word + "way"

  # Checking for vowel index
  for i in range(1, len(word)):
      # Checking for vowels(including y)
       if word[i] in ['a','e','i','o','u','y']:
       # Updating vowel index
       vowelIndex = i;
       break;

  # Forming pig lating word      
   return    word[vowelIndex:] + word[0:vowelIndex] + "ay";


 def removePunctuation(text):
  """
   Removes punctuation from text
  """

  # List of punctuation characters
  punctuations = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]

   # Iterating over punctuations
   for ch in punctuations:
   # Replacing punctuations
   text = text.replace(ch, "")

   # Returning text
   return text


  def main():
  """
   Main function
   """
   # Reading line of text
   text = input("\n Enter a line of text: ")

   # Removing punctuation
   text = removePunctuation(text)

   # Converting to lower case
   text = text.lower()

 print("\n\n Pig Latin form: \n");

  # Iterating over words
  for word in text.split(" "):

   # Converting word to Pig Latin form
   word = pigLatin(word)

   # Printing word
   print(word, end = " ");

   print("\n");


  # Calling main function
  main()

我到底该如何添加一个循环来请求用户继续或不继续?我是编程新手,我很困惑。我也不明白如何在猪拉丁形式之前加上英语形式的句子?? 有人能帮忙吗


Tags: oftextinformforreturndefword
2条回答

一个简单的解决方案可能如下所示:

while True:
    main()

    response = input("Continue?")
    if response != 'y':
        break

您可能希望对接受的输入不那么严格

我认为最好将这个循环放在主函数中(在调用它之前检查一下__name__),但这至少说明了这个循环是什么样子

可以在main中使用while循环和-1之类的字符串退出

def main():
   while True: 
   """
   Main function
   """
   # Reading line of text
   text = input("\n Enter a line of text or -1 to exit: ")
   if text == '-1':
      exit(0)
   # Removing punctuation
   text = removePunctuation(text)

   # Converting to lower case
   text = text.lower()

 print("\n\n Pig Latin form: \n");

  # Iterating over words
  for word in text.split(" "):

   # Converting word to Pig Latin form
   word = pigLatin(word)

   # Printing word
   print(word, end = " ");

   print("\n");

相关问题 更多 >