我是初学者,我刚刚开始学习如何编写python代码。这个我有问题。每当我输入正确的结果时,它仍然显示它是不正确的。我想知道我错过了什么,或者我做错了什么。
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer: ")
array1.reverse()
arrayAns = array1
if userAns == arrayAns:
print("You are correct")
else:
print("You are incorrect")
当您使用input()
时,指定的变量将默认为string
类型,因此,与数组比较时总是返回false。
但是,如果您打算以字符串格式返回列表,您应该尝试使用ast.literal_eval()来计算您作为输入函数的答案传递给的字符串。
考虑:
import ast
userAns = ast.literal_eval(input("Enter your answer: "))
发送后:
[25,20,15,10,5]
您将得到如下结果:
You are correct
因为您传递的字符串作为问题('[25,20,15,10,5]')的答案将被计算并识别为一个列表,然后,当将其与另一个变量进行比较时,将计算为True。
input
只返回str
值。你要么把"倒转";数组转换为str
或将输入转换为numpy数组。第一个选项似乎更容易,可以是str(array1)
。
正如已经提到的,你正在尝试将用户输入的字符串与数组进行比较,因此在比较时结果将为false。
我的解决方案是:
temp = userAns.split(",")
userAns = [int(item) for item in temp]
首先将字符串拆分为一个列表。这将创建一个字符串数组。接下来通过将每个项目类型从string更改为int来重新创建数组。你最终得到一个整数数组,然后可以进行比较。
正如其他回复者所指出的,输入返回一个str。如果您愿意,您可以要求用户以逗号分隔的格式输入值,然后使用split()函数将字符串分割成一个以逗号分隔的数组,如下所示:
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer (comma delimited, please): ")
array1.reverse()
arrayAns = list(map( str, array1 ) )
if userAns.split(',') == arrayAns:
print("You are correct")
else:
print("You are incorrect")
下面是输出示例:
Question 2: What is the reverse of the following array? [5, 10, 15, 20, 25]
Enter your answer (comma delimited, please): 25,20,15,10,5
You are correct
再运行一次-让我们确保当他们输入错误的值时它能工作:
Question 2: What is the reverse of the following array? [5, 10, 15, 20, 25]
Enter your answer (comma delimited, please): 25,20,15,10,6
You are incorrect
由于用户输入的是字符串,我们需要对字符串与字符串进行比较。因此,我使用下面的map(str, array1)调用将array1中的每个整数转换为字符串。
您还可以看到,我使用split(',')将useran拆分为一个数组。
相反的方法也是可能的。我们可以用array1构造一个字符串然后比较两个字符串。在本例中,我可以使用join()函数从数组构建字符串:
arrayString = ','.join( arrayAns )
代码可以是这样的:
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer (comma delimited, please): ")
array1.reverse()
arrayAns = list(map( str, array1 ) )
arrayString = ','.join(arrayAns)
if userAns == arrayString:
print("You are correct")
else:
print("You are incorrect")