This is the question, Write a Python program to find numbers in between 100 and 400 (both inclusive) where each digit of the numbers is an even number. The numbers obtained should be printed in a comma-separated sequence. I'm only allowed to use while loops so I'm not sure how.
CodePudding user response:
You need to collect the values in a list
, and at the end print them comma-separated
x = 100
keep = []
while x <= 400:
strx = str(x)
if all(int(digit) % 2 == 0 for digit in strx):
keep.append(strx)
x = 2
print(",".join(keep))
# 200,202,204,206,208,220,222,224,226,228,240,242,244,246,248,260,262,264,266,268,280,282,284,286,288,400
CodePudding user response:
Here is a solution with only while loops and without converting to string:
i = 100
while i <= 400:
d = i
flag = True
while d > 0:
d,r = divmod(d,10)
if r%2:
flag = False
if flag:
print(i)
i = 2 # optimization as only even numbers are valid
output (as single line):
200 202 204 206 208 220 222 224 226 228 240 242 244 246 248 260 262 264 266 268 280 282 284 286 288 400
CodePudding user response:
This is just some correction to have a list with all the values at the end. With only using a while
loop.
x = 100
l = []
while x < 400:
x = 2
str_x = str(x)
if int(str_x[0]) % 2 == 0 and int(str_x[1]) % 2 == 0 and int(str_x[2]) % 2 == 0:
l.append(x)
print(l)
A more pythonic way in doing this:
l = lambda a, b : [
x for x in range(a, b 1)
if all(int(digit) % 2 == 0 for digit in str(x))
]
print(l(200, 401))