如何使输出返回一个数字?



我创建了这段代码,以便程序打印出范围(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整除的数字?

有两个bug,这里打印函数,需要返回值。如果你已经写了print,那么就调用这个函数。如果你想为x%k==0打印k,那么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))

对于这样的任务,可以使用单个推导式。

k = 6
print([x for x in range(1000, 10000) if x % k == 0])

我认为您应该尝试将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))
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))