1
我想學習Python,但我對它仍然很陌生。我試圖創建一個數字列表,從2到用戶輸入的數字,然後通過列表並從列表中刪除所有非素數,然後再打印出來。我在計算時遇到了麻煩,因爲我不斷收到錯誤:列表索引超出範圍。我正在考慮使用for循環,但是然後變量i將低於變量current,並且我需要確保當它通過列表時我總是高於當前值。我只能使用基本功能和循環來完成任務。在Python中創建一個Primes列表並打印出列表3.6.1
counter = 2
current = 2
n = int(input("Please enter a number larger than 2. "))
while counter <= n:
userList.append(counter)
counter = counter + 1
print("Printing out list ")
print(userList)
i = 1
while i <= len(userList):
if userList[ i ] % current == 0:
userList.remove(userList[i])
i = i + 1
else:
current = current + 1
print(userList)
我明白了。這個任務只允許我使用基本的循環和函數。不允許使用過濾器和lambda等關鍵字。我甚至不知道他們做了什麼。基本上,我只允許使用我在代碼中的內容,但這只是不正確的。 –
基本上,您只需從未標記爲已刪除的值中創建新列表。您可以輕鬆地將其重寫爲循環和if語句。 – gcx11