好吧,所以我正在研究Pig Latin翻译器(就像Codecademy课程中的那个,但更高级),它有效,除非我提示用户是否要翻译另一个单词,但是无论输入什么,我给用户的if / else语句总是跳到else。该模块没有语法错误或任何东西,我没有看到任何错误的代码。这是我的程序阻止给我的问题:
def translator():
job = input("Are you translating TO or FROM PygLatin? ")
if job.upper() == "TO":
word = input("Alright, what's the word we're translating? ")
wordlength = len(word)
firstletter = word[0]
choppedword = word[1:wordlength]
completeword = choppedword + firstletter + pyg
print("Okay! Your translated word is...")
time.sleep(3)
print(completeword)
time.sleep(3)
redo = input("Wanna translate something else? Y/N ")
if redo.upper == "Y":
print("Awesome!")
time.sleep(3)
translator()
else:
print("Oh, okay then... Bye " + name + "!")
sys.exit()
elif job.upper() == "FROM":
word = input("Alright, what’s the word we’re translating? ")
wordlengthtwo = int(len(word))
firstletterindex = int(wordlengthtwo - 3)
firstletter = word[firstletterindex]
choppedword = word[0:firstletterindex]
newword = str(firstletter.upper() + choppedword)
print("Okay! Your translated word is...")
time.sleep(3)
print(newword)
time.sleep(3)
again = input("Wanna translate something else? Y/N ")
if again.upper == "Y":
print("Awesome!")
time.sleep(3)
translator()
else:
print("Oh, okay then... Bye " + name + "!")
sys.exit()
更具体地说,这些部分在编码中:
redo = input("Wanna translate something else? Y/N ")
if redo.upper == "Y":
print("Awesome!")
time.sleep(3)
translator()
else:
print("Oh, okay then... Bye " + name + "!")
sys.exit()
和
again = input("Wanna translate something else? Y/N ")
if again.upper == "Y":
print("Awesome!")
time.sleep(3)
translator()
else:
print("Oh, okay then... Bye " + name + "!")
sys.exit()
那么......关于为什么会发生这种情况或如何解决它的任何想法?
答案 0 :(得分:3)
str.upper
是一种方法。如果你想要大写字符串的值,你应该调用这个方法。
答案 1 :(得分:3)
调用str.upper
函数
if redo.upper() == "Y":
...
if again.upper() == "Y":
...
答案 2 :(得分:1)
当你有:
if again.upper == "Y":
将again.upper
函数与字符串"y"
进行比较。此比较将始终为false,因此它将始终评估false分支。
其他语言不允许以这种方式使用函数,并且可能会给您一个错误,这种错误可能不是您所期望的。
如果您使用REPL或类似内容查看此内容,您会看到正在发生的事情,此代码段有望帮助您了解正在发生的事情:
test = "abcDEF"
print(test.upper)
print(test.upper())
此输出:
<built-in method upper of str object at 0xb73ce300>
ABCDEF
您可以在此处查看此操作:http://ideone.com/gYyPnH