Q:

How to check if all the digits of a number are odd in python?

I was told to solve a problem in which I would have to find out the number of 4-digit numbers which are all composed of odd digits. I tried the following python code:
new_list =[] # A list which holds the numbers
for a in range(1111,10000):
    for b in str(a):
        if int(b) % 2 == 1:
            new_list.append(a)
print len(new_list)

However, it has a flaw in the second loop's if statement which only checks if the current digit is odd and it also caused the digits to be added multiple times, not to mention they didn't meet the criteria. So how do I solve this problem using python? And if you could write a function that checks if all the numbers of a list(argument) are composed of numbers which consist of only odd/even digits, it would be great too.
Edit: I also need a list of the numbers, that's why multiplication can't do all of the work.

A:

A 4 digit number that is composed only of odd digits can only use the digits 1, 3, 5, 7 and 9. That gives you 5 to the power 4 is 625 different numbers. That didn't require trying them all out.
You can still do that of course, using itertools.product() for example:
from itertools import product

print sum(1 for combo in product('13579', repeat=4))

because product('13579', repeat=4) will produce all possible combinations of 4 characters from the string of odd digits.
Your code needs to test if all digits are odd; break out early if any digit is not odd:
new_list =[] # A list which holds the numbers
for a in range(1111,10000):
    for b in str(a):
        if int(b) % 2 == 0:
            break
    else:
        # only executed if the loop wasn't broken out of
        new_list.append(a)

You could use the all() function with a generator expression for that test too:
new_list = []
for a in range(1111,10000):
    if all(int(b) % 2 == 1 for b in str(a)):
        new_list.append(a)

which then can be collapsed into a list comprehension:
new_list = [a for a in range(1111,10000) if all(int(b) % 2 == 1 for b in str(a))]

