【问题标题】:Why does my python pig latin program output word+way every time?为什么我的python pig latin程序每次都输出word+way?
【发布时间】:2014-04-29 22:40:49
【问题描述】:

我正在尝试使用 Python 制作一个 Pig Latin 翻译器。如果单词以元音开头,则应附加“方式”。如果单词以辅音开头,则应打印第一个字母移到末尾并附加“ay”的单词。 Cat 应该打印 atcay,Apple 应该打印 appleway。但是,两者最终都有附加到末尾的方式。我解析并似乎找不到错误。我认为它与 elif 语句有关,也许它停在那里,但我是编程新手,不确定。

我做错了什么?

print('Welcome to the Pig Latin translator!')

pyg = 'ay'
word = input('Enter a word: ')
word = word.lower()

if word.isalpha() == False:                         #  Checks if string is empty and consists of only letters. 
    print('It seems that you did not enter a word, try again. ')
elif word[0] == 'a' or 'e' or 'i' or 'o' or 'u':    #  If first letter is a vowel
        print(str(word) + 'way')                    #  print variable word plus the string way
else:
    newword = word + word[0] + pyg                  #  If first letter is consonant(not vowel) and  consists of only letters
    print(newword[1:])                              #  print the word characters 1(not 0) through last

【问题讨论】:

标签: python logic semantics python-3.4


【解决方案1】:

这行是不正确的,因为它总是评估为真:

elif word[0] == 'a' or 'e' or 'i' or 'o' or 'u':

你的意思是:

elif word[0] == 'a' or word[0] == 'e' or word[0] == 'i' or word[0] == 'o' or word[0] == 'u':

您可以通过以下方式简化它:

elif word[0] in 'aeiou':

【讨论】:

  • 要扩展此答案的第一行,这是因为非空字符串将评估为 True 并且布尔逻辑(和,或)不会继承运算符( ==,>等)
猜你喜欢
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 2014-12-11
  • 2021-12-05
  • 1970-01-01
  • 2022-12-01
  • 2012-10-17
  • 2016-01-16
相关资源
最近更新 更多