首页 > 解决方案 > 使用 Python 将原始输入与数组中的特定元素进行比较

问题描述

我在 Python 中有一小段代码,我试图将用户输入与数组中的特定元素进行比较。这是代码:

movies = ["movie 1", "movie2", "movie3"];

answer = raw_input("What is your guess: ")

    if answer == movies[1]
       then print ("yes that is correct")
       else:
         print ("no that is incorrect")

我知道上面的缩进看起来不对,因为我在文本框中输入了它,而且我是这个网站的新手,也是 python 的新手。我也知道我可能需要使用某种条件循环,也许是一个 while 循环,但是我很难找到可以将用户输入字符串值与数组中的字符串值进行比较的位置。任何想法我可以如何做到这一点?

标签: pythonarraysloops

解决方案


玩得开心!我猜您正在尝试创建一个循环,该循环不断接收用户的输入以与所需的输入进行比较,直到用户键入正确的输入为止。如果是这样,一种方式,它可以实现如下(但考虑添加一个中断条件,如 input == "Bored" ,以避免无限循环和硬停止你的代码):

movies = ["movie 1", "movie2", "movie3"]
correctAnswer = movies[1]
is_notCorrect = True
while(is_notCorrect):
    answer = raw_input("What is your guess: ")
    if answer == correctAnswer:
       print("Yes, that is correct")
       is_notCorrect = False
    else:
       print("No, that is incorrect")

在上面的代码中,当 is_notCorrect 变为 False 时。在下一个条件检查时,它将打破条件,并完成循环。

您的代码有一些问题

movies = ["movie 1", "movie2", "movie3"]; # No need the semi-colon in Python

answer = raw_input("What is your guess: ") 
# Need a colon here after if condition, new line, and indent. 
#If you don't like the colon, you need to write a different way with one line of code Eg: <Do A> if <Condition happens> else <Do B> 
if answer == movies[1]     
   then print ("yes that is correct") # No then in if-else statement in Python 
   else:
     print ("no that is incorrect")

推荐阅读