3 回答

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

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

TA貢獻1891條經驗 獲得超3個贊
正如所提供的輸出所解釋的,問題出在代碼的第 9 行。
while target != randnums:
這將檢查target
變量是否不等于 randnums 變量(一個 numpy 數組)。
你真正想要的是這個
while target not in randnums:
randnums
如果變量的值target
是 numpy 數組中的值之一 ,它將迭代變量并返回一個布爾值randnums
。
添加回答
舉報