【问题标题】:Simple python code repeating an else statement, and i don't know why [closed]简单的python代码重复一个else语句,我不知道为什么[关闭]
【发布时间】:2017-09-14 21:27:02
【问题描述】:

所以我是 python 新手,刚刚开始创建一个带有菜单系统的基本程序,我将添加到该菜单系统中,以帮助在一个文件中显示我对 python 的进度和知识,并帮助我更熟悉多种功能,函数调用函数等......

我的程序在输入可使 if 语句正确的字符串后重复 else 语句。

看看:

def menuReturn():
returnAns = input("Would you like to return to the menu? [y/n] ")

if returnAns.lower == "y":
    print("Returning you to the menu")
    print("")
    print("")
    print("")
    menu()

elif returnAns.lower == "n":
    print("Exiting...")

else:
    print("Please repeat the answer")
    menuReturn()

def askName():
    name = input("What is your name? ")
    print(name + "? Thats a beautiful name!")
    menuReturn()

def menu(menuAnswer):
    if menuAnswer.lower == "askname":
        print("Good Choice!")
        askName()

    else:
        print("Please try again")
        menu(menuAnswer)

print("Welcome to the menu!")
print("")
print("Please enter a keyword from the following")
print("")                                                                       
#Add items here!
print("-askName")
menuAnswer = input("")
menu(menuAnswer)

我不得不添加一些不必要的缩进来发布这个问题,很抱歉

请给出一个简单的答案,因为我的编程“行话”没有满负荷

希望尽快收到您的来信, 约翰·弗莱彻

【问题讨论】:

    标签: python function if-statement iteration


    【解决方案1】:

    returnAns.lower 返回字符串的内置低层函数<built-in method lower of str object at 0x*>,而不是调用它的结果。这就是为什么else 似乎重复,if 条件正确失败的原因。你想调用lower函数:

    returnAns.lower() # returns the lowercase returnAns
    

    【讨论】:

      【解决方案2】:

      @TheoretiCAL 是对的。您希望对字符串变量的函数调用是 returnAns.lower() 而不是 returnAns.lower

      不同之处在于 str.lower() 返回一个全小写字符的字符串,而 str.lower 不是有效的运算符,根据此处的 python 字符串说明:https://docs.python.org/2/library/string.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 2022-08-09
        • 2016-07-24
        • 1970-01-01
        • 2023-03-29
        相关资源
        最近更新 更多