首页 > 解决方案 > 为什么即使布尔值到位,我的条件分支也不会打印?

问题描述

我做了一个非常简单,愚蠢的程序只是为了练习。为什么最后一部分不打印我想要打印的内容?

string1=input("Write any food that begins with the letter 'a'")
string1.lower()

if string1.startswith("a")==True:
  print("Good job")
elif string1.startswith("a")==False:
  print("Are you sure you know what the letter 'a' is?")

string2=input("Now, write any food that ends with 'b'.")
string2.lower()

if string2.endswith("b")==True:
  print("That's right!")
elif string2.endswith("b")==False:
  print("No, that's not right.")

fruits=input("Now, enter five different fruits, separated by commas.\n")
fruits.split(",")
list1=[fruits]

print("Now, let's see if %s is in this list"%string1)

if string1 in list1==True:
  print("Yes, it is")
elif string1 in list1==False:
  print("No, it isn't.")

print("Now, let's see if %s is in this list"%string2)

if string2 in list1==True:
  print("Good work")
elif string2 in list1==False: 
  print("Not true")

无论我写什么,“好作品”、“不是真的”和“是的,它是”等都不会打印出来。请指教。谢谢!

标签: pythonprintingboolean

解决方案


分解问题

让我们一步一步来:

  1. if string1 in list1==True:

评估的第一件事是list1 == True哪个将返回False,因为list1不等于True

现在我们有了这个:

  1. if string1 in False:

这将返回 False 因为string1不在布尔值中False

所以你所有的陈述都会返回 False


修复?

  1. if string1 in list1:

只需从您的陈述中删除==True或。==False

如果您想评估错误使用not

if string1 not in list1:或者你可以说if not (string1 in list1):

希望这可以帮助!如果您有任何问题,请发表评论。


稍后再进行一些调整

尝试这个

string1=input("Write any food that begins with the letter 'a'")
string1.lower()

if string1.startswith("a")==True:
  print("Good job")
elif string1.startswith("a")==False:
  print("Are you sure you know what the letter 'a' is?")

string2=input("Now, write any food that ends with 'b'.")
string2.lower()

if string2.endswith("b")==True:
  print("That's right!")
elif string2.endswith("b")==False:
  print("No, that's not right.")

fruits=input("Now, enter five different fruits, separated by commas.\n")
fruits = fruits.split(",")
list1=[fruit.strip(' ') for fruit in fruits]

print("Now, let's see if %s is in this list"%string1)

if string1 in list1:
  print("Yes, it is")
elif string1 not in list1:
  print("No, it isn't.")

print("Now, let's see if %s is in this list"%string2)

if string2 in list1:
  print("Good work")
elif string2 not in list1: 
  print("Not true")

需要注意的事情,当你按照你的方式制作列表,然后用逗号分隔时,你不小心在每个单词后有一个额外的空格'',所以即使你检查'apple'是否在列表中并且它在列表,它会返回 false 因为 'apple ' 将在列表中(注意空格)。这就是fruit.strip(' ')生产线正在处理的事情。


推荐阅读