我已經創建了一個程序,可以成功檢測到一個數字是否爲素數,如果不是,它也會返回一個數字因子列表,但是那部分不成功。Python:錯誤的輸出和ValueError:Prime因素造物主
這裏是我的代碼:
def prime_num():
num = int(input("Give me a number...: "))
prime = True
if num == 1:
prime = False
elif num == 2:
prime = True
for x in range(2, num):
if num % x == 0:
prime = False
break
if prime == False:
print("That's not a prime number!")
factors(num)
elif prime == True:
print("That's a prime number!")
def factors(num):
factors = []
for x in range(1, num+1):
if num % x == 0:
factors.append(x)
print("The factors for " + str(num) + " are: ", factors)
for x in factors:
for y in range(1, x):
if x % y == 0:
factors.remove(x)
print("The prime factors for " + str(num) + " are: ", factors)
當我使用該功能的25我得到這個輸出「編號」值...
prime_num()
Give me a number...: 25
That's not a prime number!
The factors for 25 are: [1, 5, 25]
The prime factors for 25 are: [1, 25]
哪項不正確的輸出對於主要因素,我只是希望它返回:[5] (我不擔心這個因素的重要性)
但是,當我嘗試數字50,作爲我的「數字」。我得到這個輸出,一個ValueError:
prime_num()
Give me a number...: 50
That's not a prime number!
The factors for 50 are: [1, 2, 5, 10, 25, 50]
Traceback (most recent call last):
File "<ipython-input-19-12c785465e2a>", line 1, in <module>
prime_num()
File "C:/Users/x/Desktop/Python/Python Practice/primes.py", line 25, in prime_num
factors(num)
File "C:/Users/x/Desktop/Python/Python Practice/primes.py", line 40, in factors
factors.remove(x)
ValueError: list.remove(x): x not in list
我知道這意味着不知我的X不在因素,但我不知道怎麼考慮,我特別是通過迭代的因素。
請注意,在迭代同一列表時從列表中刪除值將跳過某些元素。迭代迭代:'for x [in] [:]'。 –