亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當用戶必須輸入隨機數的值時程序顯示錯誤

當用戶必須輸入隨機數的值時程序顯示錯誤

茅侃侃 2024-01-24 20:49:08
我被要求讓程序生成 15 個隨機整數的數組,然后要求用戶輸入數組中的數字并顯示一條消息,說明它在數組中,但是,我收到錯誤反而。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):  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()
查看完整描述

3 回答

?
慕田峪9158850

TA貢獻1794條經驗 獲得超7個贊

問題在于 != 和 == 運算符。

“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.")


查看完整回答
反對 回復 2024-01-24
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

較短的版本:


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')


查看完整回答
反對 回復 2024-01-24
?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

正如所提供的輸出所解釋的,問題出在代碼的第 9 行。

 while target != randnums: 這將檢查target變量是否不等于 randnums 變量(一個 numpy 數組)。

你真正想要的是這個

while target not in randnums:randnums如果變量的值target是 numpy 數組中的值之一 ,它將迭代變量并返回一個布爾值randnums。


查看完整回答
反對 回復 2024-01-24
  • 3 回答
  • 0 關注
  • 252 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號