[英]Why does my else statement run when my if statement is true?
這是我的代碼。 我應該問用戶他們最喜歡的書是什么,如果他們的書與我告訴他們的我的其中一本書匹配,否則我說這不是我的最愛之一。 我遇到的問題是當我在中放入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()
您需要一個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))
邏輯的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
邏輯 :您將要檢查用戶的書是否在您的列表中,然后根據該書來打印相關的消息。
建議 :
代碼 :這是您要查找的內容:
#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
添加中斷:
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.