Python:如何匹配用户输入和不区分大小写的答案?

2024-05-14 08:54:51 发布

您现在位置: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!")

我使用的是python3和Wing ide101。有什么建议吗?在


Tags: the答案代码用户程序示例定义作业
2条回答

我敢打赌,你真正的问题是你在使用python3。在

例如,也许你在Mac电脑上,你没有意识到你已经安装了Python2.7。因此,您安装了Python3.4,然后安装了一个IDE,并假设它必须使用3.4,因为这就是全部功能,但它实际上默认为2.7。在

验证这一点的一种方法是import sys和{}。在

在Python2.7中,input相当于Python3的eval(input(…))。因此,如果用户键入chloroplast,Python将尝试将chloroplast作为一个Python表达式求值,这将引发NameError: 'chloroplast' is not defined。在

解决方案是找出在IDE中配置默认Python版本的位置,并为python3配置它。在

我还假设问题是您无意中使用了Python2。让代码在两个版本的Python中运行的一种方法是使用plantcell = str(input(q1))或者更好(更安全)使用raw_input(相当于python3的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!")

相关问题 更多 >

    热门问题