我創建了這段代碼,以便程式將列印出范圍(1000 到 10,000)內的所有數字,如果它可以被值 k 整除,如下所示,但輸出沒有產生......我做錯了什么?
k = 6
def pincode(k: int):
for x in range(1000,10000):
if x // k == 0:
print(x)
print(pincode(k))
我應該更改什么以確保代碼列印出可被 k 整除的范圍內的所有數字?
uj5u.com熱心網友回復:
有兩個bug,這里列印函式,需要回傳值。如果您已經撰寫了 print ,那么只需呼叫該函式。如果你想列印 k forx%k==0那么 x 有多個值。您可以通過將 x 值收集到串列來回傳多個值。第二個是,它是 x%k==0 而不是 x//k==0。//給你整數商,%會給你余數。例如,49//7 是 7,49%7 是 0,26//7 是 3,26%7 是 5。你的新代碼:
k = 6
def pincode(k: int):
collect=[]
for x in range(1000,10000):
if x % k == 0:
collect.append(x)
return collect
print(pincode(k))
uj5u.com熱心網友回復:
您可以使用單個理解來完成此類任務。
k = 6
print([x for x in range(1000, 10000) if x % k == 0])
uj5u.com熱心網友回復:
我想你應該嘗試改變//在if x // k == 0:到%這是操作員,回傳余代替商。
您的函式pincode(k)沒有return引數,因此它回傳none. 將值附加到串列中,然后將該串列添加到return引數中。
k = 6
def pincode(k: int):
a = [] #empty list
for x in range(1000,10000):
if x % k == 0: # use % instead of //
a.append(x) # append x to list
return a #return the list
print(pincode(k))
uj5u.com熱心網友回復:
The double forward slash in Python is known as the integer division operator. Essentially, it will divide the left by the right, and only keep the whole number component.
我建議使用 % 來查找數字是否可整除。
k = 6
def pincode(k: int):
for x in range(1000,10000):
#print(f"x and k {x} and {k} res {x%k}")
if x % k == 0:
print(x)
print(pincode(k))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/327235.html
