当用户必须输入随机数的值时程序显示错误

我被要求让程序生成 15 个随机整数的数组,然后要求用户输入数组中的数字并显示一条消息,说明它在数组中,但是,我收到错误反而。


import numpy as ny

randnums = ny.random.randint(1,101,15)


print(randnums)


target = int(input("Please pick a random number: "))


for counter in range(0,15):

  while target != randnums:

    print("This number is not in the list")

    target = int(input("Please pick a random number: "))

  else:

   if target == randnums:

      print("The number" , target , "has been found in the list.")

输出:


Traceback (most recent call last):

  File "python", line 9, in <module>

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


茅侃侃
浏览 172回答 3
3回答

慕田峪9158850

问题在于 != 和 == 运算符。“randnums”是元素列表。您无法将单个值与整个列表进行比较。相反,您想要检查该值是否在列表中。您可以使用“in”和“not in”运算符来做到这一点,因此您的代码将如下所示:import numpy as nyrandnums = ny.random.randint(1,101,15)print(randnums)target = int(input("Please pick a random number: "))for counter in range(0,15):&nbsp; while target not in randnums:&nbsp; &nbsp; print("This number is not in the list")&nbsp; &nbsp; target = int(input("Please pick a random number: "))&nbsp; else:&nbsp; &nbsp;if target in randnums:&nbsp; &nbsp; &nbsp; print("The number" , target , "has been found in the list.")

萧十郎

较短的版本:import numpy as nyrandnums = ny.random.randint(1, 101, 15)while True:&nbsp; &nbsp; target = int(input('Please pick a random number: '))&nbsp; &nbsp; if target in randnums:&nbsp; &nbsp; &nbsp; &nbsp; print(f'The number {target} has been found in the list')&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print('This number is not in the list')

万千封印

正如所提供的输出所解释的,问题出在代码的第 9 行。 &nbsp;while target != randnums:&nbsp;这将检查target变量是否不等于 randnums 变量(一个 numpy 数组)。你真正想要的是这个while target not in randnums:randnums如果变量的值target是 numpy 数组中的值之一&nbsp;,它将迭代变量并返回一个布尔值randnums。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python