【问题标题】:Write a Python program that requests a word (in lowercase letters) as input and translates the word into Pig Latin编写一个 Python 程序,请求一个单词(小写字母)作为输入并将该单词翻译成 Pig Latin
【发布时间】:2020-01-28 15:38:34
【问题描述】:

我需要编写一个 Python 程序,请求一个单词(小写字母)作为输入,并将该单词翻译成 Pig Latin。 • 将单词翻译成 Pig Latin 的规则如下: a) 如果单词以 元音 开头,则在单词末尾添加方式。例如,else 变成 elseway。 b) 如果单词以一组辅音开头,将它们移到单词的末尾并添加ay。比如chip变成ipchay。

我目前的编码:

word = input("Enter word to translate: ")
#if the 1st letter of a word is "aeiou", add "way" to the end of the word 
if word[0] == "a" or "e" or "i" or "o" or "u":  
    print(word + "way")
elif word[0] and word[1] == "b" or "c" or "d" or "f" or "g" or "h" or "j" or "k" or "l" or "m" or "n" or "p" or "q" or "r" or "s" or "t" or "v" or "x" or "y" or "z":
    print(word + "ay")

看来我目前的编码有一些问题,因为它只显示单词,在单词的末尾添加“方式”,而不管单词的第一个字母是元音还是辅音。另外,如果它是一组辅音,我不确定如何将单词的第一个字母移动到单词的末尾,并且如果单词中的第一个字母和第二个字母形成辅音,我不知道如何处理“zh”、“ch”等

这个 Python 程序的预期结果: 输入要翻译的单词:否则 Pig Latin 中的单词是 elseway。 输入要翻译的单词:chip Pig Latin 中的单词是 ipchay。

【问题讨论】:

标签: python python-3.x logical-operators


【解决方案1】:

Python 解释您的 if 语句的方式与您的想法不同。

if word[0] == "a" or "e"

我认为你认为它是:

if word[0] == ("a" or "e")

但它实际上被处理为

if (word[0] == "a") or ("e"): 

所以 word[0] 实际包含什么并不重要,因为“e”(或任何非空字符串)总是会被 Python 评估为 True,所以它总是会添加 'way'。

重写if的最简单方法是

if word[0] in "aeiou":

这实际上会检查它是否是元音,通过检查它是否出现在字符串“aeiou”中

【讨论】:

    【解决方案2】:

    'or' 不像你想象的那样工作。它查看左侧的内容是否为真,如果不是,则“或”查看右侧的内容是否为真。如果其中任何一个为 True,则“或”返回 True,否则返回 False。在您的代码中,一个字母被转换为布尔值,并且总是给出 True。所以'or'的右边总是True,这意味着你的第一个'if'总是有效的。

    【讨论】:

      【解决方案3】:

      这可能不是最pythonic的答案,但是...

      当您使用 elif: 时,您正在添加到第一个语句,这就是为什么它总是在末尾添加方式

      使用 elif 来处理每个元音,然后使用 else 语句来处理辅音:

      vowels = ['a','e','i','o','u']
      consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
      word = input("Enter word to translate: ")
      #if the 1st letter of a word is "aeiou", add "way" to the end of the word 
      if word[0] in vowels:
          print(word + "way")
      
      elif word[0] and word[1] in consonants:  
          print(word[2:] + word[0:2] + "ay") 
      
      else:
          print(word[1:] + word[0] + 'ay')
      

      【讨论】:

      • 我最初的答案没有同时考虑两个辅音,这段代码可以。
      • 也在考虑...如果您需要考虑三个辅音 (christopher),请添加另一个 elif 语句。 elif word[0:3] 在辅音中: print(word[3:] + word[0:3] + "ay")
      • 我已经尝试过你的改进代码,但不幸的是它仍然没有考虑到两个辅音。例如,我输入“chip”,它仍然显示错误的输出 (hipcay) ,而不是 ipchay。
      • 另外,如果说明要明确使用小写,那么你的第一个 if 语句应该是关于某人输入一个大写字母返回:所有字母都必须是小写
      • 我不知道为什么,因为我只是复制了您的代码,但它仍然显示“hipcay”而不是 ipchay。你之前运行过代码吗?
      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      相关资源
      最近更新 更多