为什么我的else语句在if语句为true时运行?

2024-04-19 12:50:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码。我应该问用户他们最喜欢的书是什么,如果他们的书和我的书匹配,我就告诉他们,如果不匹配,我就说它不是我最喜欢的书。我遇到的问题是,当我把一个真实的语句放进去时,我的else语句就会打印出来。例如,如果我输入“简爱”,它会打印if语句“我们都喜欢简爱!”下面的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()

Tags: inforlenifismainmytop
3条回答

逻辑的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

逻辑:您需要检查用户的书籍是否在您的列表中,然后基于此,您需要打印相关消息。你知道吗

建议

  • 我不知道这是否是你想要的,但我只会打印图书列表中的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

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

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语句仍提前退出循环,即循环直到实际尝试将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))

相关问题 更多 >