使用函数而不是循环进行Python验证

时间:2019-05-17 10:54:09

标签: python

在StackOverflow上没有答案,所以我在这里问这个问题。

该程序的基础是将要求用户输入12来查看或添加分数。如果用户输入任何其他输入,我希望它返回到函数的开头,但带有错误消息。

这样,程序不必有很多循环,只需要在出错时调用函数即可。

def view_scores ():
    print ("Type 1 to view all scores.")
    print ("Type 2 to view scores for a specific team.")
    scorecheck = input("Please type a number: ")
    if scorecheck == "1":
        f = open("scores.txt", "r")
        for line in f:
            allscores = f.readlines()
        print(allscores)
        f.close()
        program_end()
    elif scorecheck == "2": 
        teamcheck= input ("Please enter the Individual/Team name: ")
        program_end()

    elif scorecheck() not in ('1', '2'):
        print ("Not a valid input - please enter either 1 or 2")
        view_scores()

这个想法是,如果输入为1或2,它将执行该步骤,然后执行该函数以结束程序。如果不是1或2,它将要求用户输入1或2,然后再次启动该功能,因为他们在此功能上失败了。我得到TypeError: 'str' object is not callable

任何答案将不胜感激。预先感谢。

EDIT 以为这是要寻求帮助,我现在有一个答案,这不是错字,是误用了函数。绝对值得让我的帐户失去发布功能

2 个答案:

答案 0 :(得分:2)

您的scorecheck是输入中提供的字符串,您试图在此处将其作为函数调用:

elif scorecheck() not in ('1', '2'):

只需删除()中的scorecheck()


P.S。递归调用view_scores()的想法非常糟糕,请尝试避免这种行为。好的主意是使用break if语句创建无限循环:

def view_scores ():
    print ("Type 1 to view all scores.")
    print ("Type 2 to view scores for a specific team.")
    print ("Type q to quit.")
    while True:
        scorecheck = input("Please type a number: ")
        if scorecheck == 'q':
            break
        elif scorecheck == "1":
            # WAKA
            pass
        elif scorecheck == "2": 
            # WAKA
            pass
        else:
            print ("Not a valid input - please enter either 1 or 2")

答案 1 :(得分:1)

elif scorecheck() not in ('1', '2'):

应该是

elif scorecheck not in ('1', '2'):

在程序中,scorecheck是字符串,而不是函数。

相关问题