如果任何问题的答案为否,如何打印特定文本

时间:2018-11-26 16:52:01

标签: python

我遇到一个提出5个问题的问题。如果其中任何一个答案为“否”,则应打印ALIEN!否则很酷。 这是到目前为止我得到的:

human = input("Are you human? ")
human = input("Are you living on planet Earth? ")
human = input("Do you live on land? ")
human = input("Have you eaten in the last year? ")
human = input("Is 2 + 2 = 4? ")
if human == "yes":
    print("Cool")
elif human == "no":
    print("ALIEN!")`

4 个答案:

答案 0 :(得分:2)

您可以使用any()检查问题的答案是否为'no'并相应地打印消息:

human = [input("Are you human? "), input("Are you living on planet Earth? "), 
         input("Do you live on land? "), input("Have you eaten in the last year? "), input("Is 2 + 2 = 4? ")]

if any(x.lower() == 'no' for x in human):
    print('ALIEN!')
else:
    print('Cool')

答案 1 :(得分:0)

您拥有的变量human每次都会更改,并使用input()赋予新值,尝试制作多个变量,而不仅仅是使用human。

human = input("Are you human? ")
var1 = input("Are you living on planet Earth? ")
var2 = input("Do you live on land? ")
var3 = input("Have you eaten in the last year? ")
var4 = input("Is 2 + 2 = 4? ")
if(human == "yes"):
    print("Cool")
elif(human == "no"):
    print("ALIEN!")

答案 2 :(得分:0)

如果您不担心存储变量,只关心以下问题之一是否为“ no”或“ n”:

x=["human?","on earth?", "on land?","someone who eats food?","sure that 2+2=4?"]

for i in x:
    if input("Are you {}".format(i)).lower() in ['no','n']:
        print("Alien!")
        break
    else:
        print("Cool")

答案 3 :(得分:0)

请注意:在这里,您可以看到使用 for循环的一个很好的例子,因为有很多重复的代码。我个人将执行以下操作来解决此问题。

  1. 创建问题列表
  2. 遍历问题列表
  3. 如果没有答案,请中断并打印Alien。

现在输入代码:

# Initialize our list
lst = ["Are you human? ", "Are you living on planet Earth? ","Do you live on 
land? ","Have you eaten in the last year? ","Is 2 + 2 = 4? "]

#Create a flag for Alien
flag = False

#Iterate through the list
for question in lst: 
  answer = input(question)
  if answer == 'no':

    #Print alien
    print('Alien')

    #Change Flag
    flag = True

    #Break out of the loop
    break
#Check to see if our flag was thrown during the loop
if flag == False:
  print('cool')

如果您需要更多帮助来解决此类编码难题,请查看python课程简介:https://exlskills.com/learn-en/courses/learn-python-essentials-for-data-science-intro_to_python/content