2014-09-28 216 views
-1

好的,所以我刚开始学习python,我有一个任务是要求我创建一个测验。我已经想出了如何区分大小写,但我在用户输入的答案中遇到了问题。当我尝试运行程序来验证它是正确的答案时,它只是告诉我输入的答案没有被定义。Python:如何将用户输入与不区分大小写的答案进行匹配?

这里是我当前的代码示例(不要判断愚蠢的问题,我有一个大作家块:P):

q1= "1. What is the name of the organelle found in a plant cell that produces chlorophyll?" 
plantcell=input(q1) 
ans1= "chloroplast" 
if plantcell.lower()==ans1.lower(): 
    print("Correct!") 
else: 
    print("Incorrect!") 

我使用python 3和荣IDE 101.任何建议?

+0

请发布确切的错误 – User 2014-09-28 03:24:54

+0

请更好地解释你的问题你确实要做什么,错误究竟是什么(如果你遇到异常,将异常追溯粘贴到你的问题中,不要只描述它)。当我在Python 3.4中运行这个代码时,它确实听起来像你想要的。 – abarnert 2014-09-28 03:24:55

+0

请修改您的帖子以包含完整的回溯 – inspectorG4dget 2014-09-28 03:24:56

回答

1

我敢打赌,你真正的问题是,你不使用Python 3

例如,也许你是在Mac上,你没有意识到,你已经有 Python 2.7安装。所以你安装了Python 3.4,然后安装了一个IDE,并且假设它必须使用3.4,因为这就是所有这些,但实际上它默认为2.7。验证此

一种方式是import sysprint sys.version

在Python 2.7,input是Python 3的eval(input(…))等效。因此,如果用户键入chloroplast,Python是要尝试评估chloroplast作为一个Python表达式,这将提高NameError: 'chloroplast' is not defined

解决的办法是找出你配置你的IDE默认的Python版本,并将其配置为Python 3

0

我也认为这个问题是你不小心使用Python 2.一种方法让你在Python的两个版本代码的运行将是要么使用类似plantcell = str(input(q1))甚至更​​好(更安全)使用raw_input(相当于到Python 3的input下面是一个例子:

import sys 

q1 = "1. What is the name of the organelle found in a plant cell that produces chlorophyll?" 

if sys.version_info[0] == 3: 
    plantcell = input(q1) 
else: 
    plantcell = raw_input(q1) 

ans1 = "chloroplast" 
if plantcell.lower() == ans1.lower(): 
    print("Correct!") 
else: 
    print("Incorrect!") 
相关问题