Home > Enterprise >  How to code "Find Numbers Divisible by Another Number" using lists inside funciton?
How to code "Find Numbers Divisible by Another Number" using lists inside funciton?

Time:04-28

I am unable to run the above code, can you pls help me with the code and where I am going wrong:

    list1 = []
    for i in range(1,no):
        list1.append(ele)
        for i in list1:
            if (i%n == 0):
                print(i)

n = int(input("enter a number: "))
no = int(input("enter total number of elements:"))
print("enter numbers:")
ele = int(input())
print("all numbers divisible by",n,"between 1-50 are:", myf(n,no,ele))```

CodePudding user response:

You can do this with list comprehension:

def divisible(lst, n):
    return [i for i in lst if not i % n]


n = int(input("enter a number: "))
no = int(input("enter total number of elements:"))

list1 = list(range(1, no 1))

print(list1)
divisible(list1, n)

Ouput (with no=10 and n=3):

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[3, 6, 9]

EDIT: And editing OPs code so that it works gives:

n = int(input("enter a number: "))
no = int(input("enter total number of elements:"))


def myf(n, no):
    list1 = []
    for i in range(1,no 1):
        if not i%n:
            list1.append(i)
    return list1


print(f"All numbers divisible by {n} between 1 and {no} (inclusive) are: {myf(n,no)}")

CodePudding user response:

I worked with your code and made lots of changes. I believe you wanted your code like this.

n = int(input("enter a number: "))
no = int(input("Enter Last number of range:"))

print ("all no divisible by ", n ,"between 1-", no, "are:")

for i in range(1,no):
    if (i%n == 0):
        print(i)

CodePudding user response:

what you are doing slightly wrong here is taking a 3rd argument ele in your function definition def myf(n,no,ele)
while your function can work perfectly fine by taking just 2 arguments
which are the range(1-50) and the number you wanna divide it with.

making your code look even simpler and cleaner.

def myf(yourRange,dividedBy):
        finalList = []
        for i in range(1,yourRange 1):
            if i%dividedBy == 0:
                finalList.append(i)
        return finalList
    
myRange = int(input("enter total number of elements:"))
dividingNumber = int(input("enter a number: "))

print("all numbers divisible by",dividingNumber,"between 1-{a} ( including {a} ) are:".format(a=myRange), myf(myRange,dividingNumber))

your output will be:

enter total number of elements:10
enter a number: 2
all numbers divisible by 2 between 1-10 ( including 10 ) are: [2, 4, 6, 8, 10]
  • Related