python 如何修复我的输出这个代码返回“正确”?

deikduxw  于 2022-12-10  发布在  Python
关注(0)|答案(4)|浏览(177)

我是一个初学者,我刚刚开始学习如何编写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")
sf6xfgos

sf6xfgos1#

当你使用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。

8yoxcaq7

8yoxcaq72#

input只返回一个str值。你必须将“reverted”数组转换为str,或者将输入转换为numpy数组。第一个选项似乎更简单,可以是str(array1)

rm5edbpk

rm5edbpk3#

如前所述,您尝试将用户输入的字符串与数组进行比较,因此在比较时结果将为false。
我的解决办法是:

temp = userAns.split(",")
userAns = [int(item) for item in temp]

首先将字符串拆分成一个列表,这将创建一个字符串数组,然后通过将每个项的类型从string改为int来重新创建数组,最后得到一个可以比较的整数数组。

bbuxkriu

bbuxkriu4#

正如其他响应者所指出的,input返回的是一个字符串。如果愿意,可以要求用户以逗号分隔的格式输入值,然后使用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,array 1)调用将array 1中的每个整数转换为字符串。
您还可以看到,我使用split(',')将userAns拆分为一个数组。
相反的方法也是可行的。我们可以从array 1构建一个字符串,然后比较字符串。在这种情况下,我可以使用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")

相关问题