【问题标题】:Comparing raw input to an specific element in an array using Python使用 Python 将原始输入与数组中的特定元素进行比较
【发布时间】:2019-11-08 21:50:32
【问题描述】:

我在 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 循环,但是我很难找到可以将用户输入字符串值与数组中的字符串值进行比较的位置。有什么想法可以做到这一点吗?

【问题讨论】:

  • 你的 if/else 语法错误。我认为你与 bash 脚本语法混合在一起。
  • 欢迎来到 StackOverflow。 On topichow to ask 和 ...the perfect question 在此处申请。 StackOverflow 是针对特定 编程问题的知识库——不是设计、编码、研究或教程资源。修正您的缩进,查看您的材料以读取输入,并print 输出变量值以准确地了解您正在处理的内容。
  • 如果您不确定是否需要 while 循环,请查看有关 while 循环的教程,了解它们解决了哪些小问题。查看有关编写if 的教程;您的程序在某些方面在语法上是不合法的,所以这还没有准备好成为 Stack Overflow 问题。
  • 老实说我找不到任何帮助,我一直在寻找一段时间

标签: python arrays loops


【解决方案1】:

享受 Python 的乐趣!我猜您正在尝试创建一个循环,该循环不断接收用户的输入以与所需的输入进行比较,直到用户键入正确的输入为止。如果是这样,一种方式,它可以实现如下(但考虑添加一个中断条件,如 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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2021-06-24
    • 1970-01-01
    相关资源
    最近更新 更多