python - 使用 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 循环,但是我很难找到可以将用户输入字符串值与数组中的字符串值进行比较的位置。任何想法我可以如何做到这一点?
解决方案
玩得开心!我猜您正在尝试创建一个循环,该循环不断接收用户的输入以与所需的输入进行比较,直到用户键入正确的输入为止。如果是这样,一种方式,它可以实现如下(但考虑添加一个中断条件,如 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")
推荐阅读
- android-studio - 在 Java (Android Studio) 中从 Activity 转换为 Fragment 时,Bottom_nav_menu 消失
- apache-nifi - 如何使 jsonpath 为名称-值对工作
- mongodb - 未处理的拒绝 Mongo 错误:在运行 mocha 测试时获取 addrinfo ENOTFOUND
- pandas - 我想知道使用熊猫的唯一类别编号
- node.js - 我可以使用 Express 创建客户端应用程序吗?
- c# - 如何使用 mysql 启用实体框架?
- ember.js - Ember Octane Glimmer 组件 @actions 是如何调用的?
- sql - 在一个查询中组合多个 SELECT 语句
- r - 如何通过在 R 中的大型数据框中进行观察来获得前 n 个距离?
- wordpress - Microsoft-IIS/7.5 服务器上的 Wordpress:只有主页有效