[英]Write a program to print first x terms of the series 3N + 2 which are not multiples of 4
[英]python program, Write a program to print first x terms of the series 3N + 2 which are not multiples of 4
我已經編寫了一個程序,但我沒有找到我做錯的地方請幫助這里是下面的代碼我首先獲取 output 並將其存儲在列表中然后我只想從列表中獲取前 10 個數字但是我我收到關於 n 的錯誤,因為 n 無法從這個 scope 開始訪問...請檢查並建議更正。問題很簡單,不要評判我
def termsAp(n):
for x in range(1,n+1000,1):
num=3 * x + 2
if num%4!=0:
li=[]
li.append(num)
for i in li[0:n]:
print(i,end=' ')
n=int(input())
termsAp(n)
如果您的程序的目標是獲取前 10 個數字,可以采用以下方法。
def termsAp(n):
li = []
for x in range(1, n + 1000, 1):
num = 3 * x + 2
if num % 4 != 0:
li.append(num)
return li[:n]
n = int(input())
termsAp(n)
主要區別在於,即使您仍然對所有 1000 個數字進行運算,您也只保留需要的那些。 我還添加了返回function,這樣更容易理解function的目的。
n = int(input())
count = 1
i = 1
while(count <= n):
num = 3*i + 2
if num % 4 != 0:
print(num, end=" ")
count +=1
i += 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.