在Codeacademy上学习python。 这是Pig Latin Translator的一个简单程序。 正如标题所说,根据先前的输入(故意输入不正确),该函数返回不同的(第一)值而不是最新的值,如果否则清除。我试图将return放在其他内部,但是在#Reference中看到,不返回局部变量。请帮忙。
def string_check():
name = raw_input("Enter a word")
if len(name) == 0 or name.isalpha() == False:
print "Enter a valid word"
string_check()
else:
print name
return name
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = string_check()
print ("Original variable is " +original)
ans = original[1:len(original)] + original[0] + "ay"
print ("Pig Latin word is %s"% (ans))
# Reference
omega = 3
if omega == 3:
print "Obvious"
beta = 5
print beta
print beta
1:当我输入空白作为第一个输入时
Welcome to the Pig Latin Translator!
Enter a word
Enter a valid word
Enter a word 123
Enter a valid word
Enter a word 123gas
Enter a valid word
Enter a word gas
gas
Original variable is
Traceback (most recent call last):
File "python", line 15, in <module>
IndexError: string index out of range
2:当我输入第一个输入为123
时Welcome to the Pig Latin Translator!
Enter a word 123
Enter a valid word
Enter a word
Enter a valid word
Enter a word 123gas
Enter a valid word
Enter a word
Enter a valid word
Enter a word gas
gas
Original variable is 123
Pig Latin word is 231ay
Obvious
5
5
None
3。当我直接输入正确的输入时
Welcome to the Pig Latin Translator!
Enter a word gas
gas
Original variable has gas
Pig Latin word is asgay
Obvious
5
5
None
答案 0 :(得分:0)
在string_check
函数内部,您在第4行调用自己。但是,未捕获返回的结果(name
)。一种解决方案是使用string_check()
替换第4行的name = string_check()
。