语法len的功能

时间:2017-05-01 12:54:15

标签: python

maxQuestions = 3
for question in firstQuestions:
    answer1 = input(question)
    while(len(answer1) == 0 or (answer1 != "yes" and answer1 != "no")):
            answer1 = input("You may only input yes or no \n" + question)
    if answer1 ==  "yes":
            print("")
    else:
        if booleanArray[firstQuestions.index(question)] == True:
            answer2 = input(firstQuestionsAnswers[firstQuestions.index(question)])
            while(len(answer2) == 0):
                 answer2 = input("You must input an answer \n" + firstQuestionsAnswers[firstQuestions.index(question)])
            answerToQuestion = finalAnswers(answer2, firstQuestions.index(question))
            print(secondQuestionAnswers[firstQuestions.index(question)] + answerToQuestion)
        else:
            print(firstQuestionsAnswers[firstQuestions.index(questionn)])

我只是一个初学者。 len在这种情况下做了什么。使用len语法是否存在任何问题或缺点。

1 个答案:

答案 0 :(得分:2)

这样的代码:

if len(answer1) == 0

通常用Python编写:

if not answer1:

字符串为空时,字符串的布尔值为False,否则为True。因此,编写第二种形式更简洁,更有效。