我为pyg latin(取自Codeacademy)编写了我非常混乱(道歉)的代码。
它可以正常工作,但我想添加 While True ...语句,以便用户输入数字或空白字段< / strong>输入框重新出现,直到满足条件
pyg='gy'
original=raw_input("please enter a word")
original_lc=original.lower()
first=original_lc[0]
rest=original_lc[1:len(original_lc)]
while True:
if len(original) >0 and original.isalpha():
print "Your word: " + original_lc
if first in "aeiou":
print "your pyglatin translation: " + original_lc + pyg
else:
print "your pyglatin translation: " + rest + first + pyg
break
else:
print "You entered a blank field or a number. Please try again."
break
我知道这是不正确的。有什么提示吗?
答案 0 :(得分:1)
您可以将循环放在开头,以便在第一个输入错误时要求用户输入新输入:
pyg='gy'
original=raw_input("please enter a word")
# keep asking for an input until the user inputs something valid
while len(original) == 0 or not original.isalpha():
print "You entered a blank field or a number. Please try again."
original=raw_input("please enter a word")
# at this point, the input should be valid
original_lc=original.lower()
first=original_lc[0]
rest=original_lc[1:len(original_lc)]
print "Your word: " + original_lc
if first in "aeiou":
print "your pyglatin translation: " + original_lc + pyg
else:
print "your pyglatin translation: " + rest + first + pyg
答案 1 :(得分:0)
对raw_input
的调用应该在你的循环中。
while True:
pyg='gy'
original=raw_input("please enter a word")
original_lc=original.lower()
first=original_lc[0]
rest=original_lc[1:len(original_lc)]
if len(original) >0 and original.isalpha():
print "Your word: " + original_lc
if first in "aeiou":
print "your pyglatin translation: " + original_lc + pyg
else:
print "your pyglatin translation: " + rest + first + pyg
break
else:
print "You entered a blank field or a number. Please try again."
break