【问题标题】:Program displays error when user has to input the value of the random number当用户必须输入随机数的值时程序显示错误
【发布时间】:2020-10-30 11:48:55
【问题描述】:

我被要求让程序生成一个由 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()

【问题讨论】:

  • 一个数字target怎么能等于一个包含15个项目的ndarray randnums
  • != 不等于。你需要not in
  • @rdas 其中一个数字需要在数组中
  • @JohnColeman 是的,如果它不等于目标,那么它需要让用户再次输入数字。
  • @mrKrauklis 但这没有任何意义。单个数字永远不会等于 15 个数字的数组。

标签: python arrays random


【解决方案1】:

问题在于 != 和 == 运算符。
“randnums”是一个元素列表。您不能将单个值与整个列表进行比较。相反,您想检查该值是否在列表中。
您可以通过使用“in”和“not in”运算符来做到这一点,因此您的代码将如下所示:

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 not in randnums:
    print("This number is not in the list")
    target = int(input("Please pick a random number: "))
  else:
   if target in randnums:
      print("The number" , target , "has been found in the list.")

【讨论】:

    【解决方案2】:

    问题是您的代码的第 9 行,正如所提供的输出所解释的那样。

    while target != randnums: 这将检查target 变量是否不等于 randnums 变量,后者是一个 numpy 数组。

    你真正想要的是这个

    while target not in randnums: 如果target 变量的值是randnums numpy 数组中的值之一,它将遍历randnums 变量并返回一个布尔值。

    【讨论】:

      【解决方案3】:

      短版:

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

      【讨论】:

      • 它实际上修改了代码......用户不想要一个无限循环,当它得到第一个匹配时就中断,用户只想重复这个代码15次
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 2018-05-07
      • 2016-03-22
      相关资源
      最近更新 更多