简体   繁体   English

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

[英]Why does my else statement run when my if statement is true?

This is my code. 这是我的代码。 I am supposed to ask the user what their favorite book is, if their book matches one of mine I tell them, if not I say it isn't one of my favorites. 我应该问用户他们最喜欢的书是什么,如果他们的书与我告诉他们的我的其中一本书匹配,否则我说这不是我的最爱之一。 The problem I'm having is when I put a true statement in , my else statement prints. 我遇到的问题是当我在中放入true语句时,打印出else语句。 So for example if I input "Jane Eyre" it would print the if statement "We both like Jane Eyre!" 因此,例如,如果我输入“ Jane Eyre”,它将打印if语句“我们俩都喜欢Jane Eyre!” And below the else statement "That is not one of my top 5 favorites, but great choice!" 在else语句下面,“这不是我的前5个最爱,但是不错的选择!”

This might be a easy fix and I am just over thinking but I would appreciate some help please! 这可能是一个简单的解决方法,我只是在考虑一下,但是请您提供一些帮助!

(The indenting might be off because of copy and paste) (由于复制和粘贴,缩进可能已关闭)

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()

You need a break statement to exit the loop early in order to avoid the else clause of the for loop: 您需要一个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!")

Even if the user inputs The Bible , the break statement still exits the loop "early", in the sense that the loop doesn't know it's on the last iteration until it actually tries to set x to the next (non-existent) value. 即使用户输入了The Bible ,break语句仍会 “提前”退出循环,因为该循环直到实际尝试将x设置为下一个(不存在)值时才知道它在最后一次迭代中。

That said, you don't actually need a loop, just the in operator: 也就是说,您实际上不需要循环,仅需要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!")

As an aside, your second loop would be more idiomatic using enumerate : 顺便说一句,使用enumerate可以使您的第二个循环更加惯用:

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

The else part of your logic is in no way associated with your if , and will execute every time your program is run regardless. 逻辑的else部分与if无关,并且无论何时运行程序都将执行。 I believe you are looking to make a function that will return the matching values. 我相信您正在寻找一个将return匹配值的函数。 This has the added benefit of reducing the number of iterations performed should a match be found. 这具有增加的好处,即如果找到匹配项,则减少执行的迭代次数。 It would look something like: 它看起来像:

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!"

You would then need to call the function that you have made like: 然后,您需要像这样调用已创建的函数:

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

Putting it together would look like: 放在一起看起来像:

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()

A sample output looks like: 输出示例如下:

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

Logic : You will want to check if the user's book is in your list and then based on that, you will want to print the relevant message. 逻辑 :您将要检查用户的书是否在您的列表中,然后根据该书来打印相关的消息。

Recommendation : 建议

  • Not sure if this is what you intended or not, but I would only print the 5 books in bookList if the user's book is different from the list. 不知道这是否是您想要的,但是如果用户的书不同于列表,我只会在bookList中打印5本书。 Code below reflects this. 下面的代码反映了这一点。
  • Rather than naming your variable bookList, I would say favBooks so it is obvious what it represents. 我会说favBooks而不是命名变量bookList,因此很明显它代表什么。

Code : This is what you're looking for: 代码 :这是您要查找的内容:

#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])

Output : 输出

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

Add break: 添加中断:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM