如果if语句为true,为什么else语句运行?

时间:2019-05-06 20:02:34

标签: python

这是我的代码。我应该问用户他们最喜欢的书是什么,如果他们的书与我告诉他们的我的其中一本书匹配,否则我说这不是我的最爱之一。我遇到的问题是当我在中放入true语句时,打印出else语句。因此,例如,如果我输入“ Jane Eyre”,它将打印if语句“我们俩都喜欢Jane Eyre!”在else语句下面,“这不是我的前5个最爱,但是不错的选择!”

这可能是一个简单的解决方法,我只是想一想,但是请您提供一些帮助!

(由于复制和粘贴,缩进可能已关闭)

def main():

    bookList = ["Jane Eyre", "To Kill a Mockingbird", "My Antonia","Pride and Prejudice", "The Bible"]

    book = input("What is your favorite book?")

    for x in range(0,len(bookList)):
        if (book == bookList[x]):
            print("We both like " + book + "!")

    else:
        print("That is not one of my top 5 favorites, but great choice!")

    print("          ")
    print("Here are my top 5 favorite books!")
    print("         ")

    for  n in range(0, len(bookList)):
        print(str(n + 1) + " " + bookList[n])

main()

4 个答案:

答案 0 :(得分:2)

为了避免break循环的loop子句,您需要一个else语句来提前退出for

for x in range(0,len(bookList)):
    if (book == bookList[x]):
        print("We both like " + book + "!")
        break
else:
    # This only executes if break is never encountered, i.e. if the
    # loop simply "runs out".
    print("That is not one of my top 5 favorites, but great choice!")

即使用户输入了The Bible,break语句 still 也会“早”退出循环,从某种意义上说,该循环直到实际执行时才知道它在最后一次迭代中尝试将x设置为下一个(不存在)值。

也就是说,您实际上不需要循环,只需要in运算符即可:

if book in bookList:
    print("We both like {}!".format(book)
else:
    print("That is not one of my top 5 favorites, but great choice!")

顺便说一句,使用enumerate可以使第二个循环更惯用:

for n, book in enumerate(book, start=1):
    print("{} {}".format(n, book))

答案 1 :(得分:0)

逻辑的else部分与if无关,并且无论您何时运行程序都将执行。我相信您正在寻找一个可以return匹配值的函数。这具有增加的好处,即如果找到匹配项,则减少执行的迭代次数。看起来像这样:

def iterate_books(user_book, book_list):
    for x in range(0, len(book_list)):
        if user_book == book_list[x]:
            return "We both like {}!".format(user_book)
    return "That is not one of my top 5 favorites, but great choice!"

然后,您需要像这样调用已创建的函数:

book = input("What is your favorite book?")
iterate_books()

将其放在一起看起来像:

def iterate_books(user_book, book_list):
    for x in range(0, len(book_list)):
        if user_book == book_list[x]:
            return "We both like {}!".format(user_book)
    return "That is not one of my top 5 favorites, but great choice!"

def main():
    bookList = ["Jane Eyre", "To Kill a Mockingbird", "My Antonia", "Pride and Prejudice", "The Bible"]

    book = input("What is your favorite book?\n>>>")
    match = iterate_books(book, bookList)
    print(match)

    print("          ")
    print("Here are my top 5 favorite books!")
    print("         ")

    for n in range(0, len(bookList)):
        print(str(n + 1) + " " + bookList[n])

main()

示例输出如下:

What is your favorite book?
>>>Jane Eyre
We both like Jane Eyre!

Here are my top 5 favorite books!

1 Jane Eyre
2 To Kill a Mockingbird
3 My Antonia
4 Pride and Prejudice
5 The Bible

Process finished with exit code 0

答案 2 :(得分:0)

逻辑:您将要检查用户的书是否在您的列表中,然后根据该书来打印相关的消息。

推荐

  • 不确定这是否是您想要的,但是如果用户的书与列表不同,我只会打印bookList中的5本书。下面的代码反映了这一点。
  • 我要说favBooks而不是命名变量bookList,所以很明显它代表什么。

代码:这就是您要查找的内容

#favorite books
bookList = ["Jane Eyre", "To Kill a Mockingbird", "My Antonia","Pride and Prejudice", "The Bible"]

#get book from user
book = input("What is your favorite book? ")

#check if user's book matches book in bookList
favBook = False
for x in range(0,len(bookList)):
    if (book == bookList[x]):
        favBook = True

#display when user's book matches book in bookList
if (favBook == True):
    print("We both like " + book + "!")
#display when user's book does not match a book in bookList
else:
    print("That is not one of my top 5 favorites, but great choice!")
    print("          ")
    print("Here are my top 5 favorite books!")
    print("         ")

    #display bookList since user's book is different from bookList
    for  n in range(0, len(bookList)):
        print(str(n + 1) + " " + bookList[n])

输出

What is your favorite book? Jane Eyre
We both like Jane Eyre!

What is your favorite book? random book
That is not one of my top 5 favorites, but great choice!

Here are my top 5 favorite books!

1 Jane Eyre
2 To Kill a Mockingbird
3 My Antonia
4 Pride and Prejudice
5 The Bible

答案 3 :(得分:0)

添加中断:

def main():

    bookList = ["Jane Eyre", "To Kill a Mockingbird", "My Antonia","Pride and Prejudice", "The Bible"]

    book = input("What is your favorite book?")

    for x in range(0,len(bookList)):
        if (book == bookList[x]):
            print("We both like " + book + "!")
            break    # <---- here

    else:
        print("That is not one of my top 5 favorites, but great choice!")

    print("          ")
    print("Here are my top 5 favorite books!")
    print("         ")

    for  n in range(0, len(bookList)):
        print(str(n + 1) + " " + bookList[n])

main()