我试图让这个while循环从输入单词的前面删除所有辅音,但是它只经过一次就结束了,我如何保持这个while循环一直到所有辅音都在单词的末尾(例如:我希望“switch”是“itch+sw”,而对于它来说,一旦辅音被移动,在末尾添加“ay”以形成“itchsway”,这是我目前的代码,我对Python非常陌生,因此任何帮助都将不胜感激!你知道吗
print("Pig Latin Translator Test!")
name = raw_input("What is your name?")
if len(name) > 0 and name.isalpha():
print("Hello!")
else:
print("That's not a name!")
word = raw_input("What is your word?")
word0 = word[0]
word0 = word0.lower()
n = 0
if len(word0) > 0 and word0.isalpha():
word0proof = word0
else:
print("That isn't a word!")
if word0proof in "aeiou":
wordoutput = word + "yay"
print (wordoutput)
else:
print("Your word doesn't begin with a vowel")
if word0proof in "bcdefghjklmnpqrstvwxyz":
word1 = word0proof
else:
word0proof = word0proof
#Now get word1 to move all consonants to the back of the word and add "ay"
这就是我在代码中遇到的问题
while word1 in "bcdefghjklmnpqrstvwxz":
word1 = word[n:] + word0 + "ay"
n = n + 1
print word1
word1 = word1
除了所有的缩进问题,我基本上只是偷了一些改进代码的想法,得到了这个(去掉了所有的变量,然后借用了元音列表中提供的while语句)
print("Pig Latin Translator Test!")
name = raw_input("What is your name, friend?")
if len(name) > 0 and name.isalpha():
print("Hello!")
else:
print("That's not a name!")
word = raw_input("What is your word?")
VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
if word[0] in VOWELS:
word = word + "yay"
else:
while word[0] not in VOWELS:
word = word[1:] + word[0]
word = word + "ay"
print (word)
正如其他人提到的,你需要修正你的压痕,并可能考虑以不同的方式解决这个问题。你知道吗
要直接回答您的问题:
您希望在循环完成后添加
"ay"
,或者最终得到多个"ay"'s
下面是一个集成到简化版代码中的循环示例。你知道吗
我在您的代码中看到许多问题: 这是多余的
else
条件,字符串中也有e
:检查首字母是否为元音或辅音的条件可以组合为:
在你的逻辑中实现你想要的:
当您仍然不知道下一次迭代是否有辅音时,您不必要地将
ay
赋值为end。我建议您首先找出要删除的字符串的多少部分,然后添加逻辑以附加ay
。像这样:也不要使用太多的
variables
这会使您的代码难以理解,例如,不需要变量word0
或word0proof
或word1
,您可以简单地作为word[0]
访问它们。你知道吗相关问题 更多 >
编程相关推荐