I created this code so that the program will print out all numbers within range (1000 to 10,000) if it is divisible by value k, as set below, but the ouput yields none.. what am I doing wrong?
k = 6
def pincode(k: int):
for x in range(1000,10000):
if x // k == 0:
print(x)
print(pincode(k))
what am I supposed to change to make sure that the code prints out all numbers within the range divisible by k?
CodePudding user response:
There are two bugs, here for printing the function, you need to return value. If you've written print already then just call the function. If you want to print k for x%k==0
then x has multiple values. You can return multiple values by collecting x values to list. The second one is, it is x%k==0 and not x//k==0. //
gives you whole number quotient and %
will give you remainder. Eg, 49//7 is 7 and 49%7 is 0 and 26//7 is 3 and 26%7 is 5. Your new code:
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))
CodePudding user response:
You can use a single comprehension for such a task.
k = 6
print([x for x in range(1000, 10000) if x % k == 0])
CodePudding user response:
I think you should try changing the //
in if x // k == 0:
to %
which is an operator that returns the remainder instead of the quotient.
Your function pincode(k)
doesn't have a return
argument, so it returns none
. Append the values to a list, then add that list to the return
argument.
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))
CodePudding user response:
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.
I would suggest to use % to find if the number is divisible.
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))