So my program checks for the number of palindrome numbers, lychrels, and non-lychrels. Originally I used a 'break' and a for loop, but I was supposed to use a while loop.
My while loop does not work the same as my for loop and I dont know what i did wrong? -- The range is meant to be between num1 and num2 also, the output is meant to be an exact copy of the prompt, so thats why it looks like this. Thanks!
Your while loop:
while (nums>=num1 and nums<=num2 and flag):
#for nums in range(num1, num2+1):
num_str = str(nums)
if num_str == num_str[::-1]:
pal += 1
else:
count = 0
num_el = num_str
while (count < 60):
np_total = int(num_el) + int(num_el [::-1])
count += 1
nums_el = str(np_total)
num_el = nums_el
if num_el == nums_el [::-1]:
nonlych += 1
flag = False
else:
lychrel += 1
print(nums, "looks like a lychrel number")
nums += 1
The
else:
lychrel += 1
print(nums, "looks like a lychrel number")
is executing every time the while
loops exits. The break
in your for
loop was skipping it.
Second problem is that when flag
is set to False
, it will stop your outer while
loop, so the first non-lychrel number you find will be the last number you test.
Here's my attempt at changing as little as possible. You can add a flag like isLychrel
instead of using the count
variable to pass information.
nums = num1
while (nums>=num1 and nums<=num2):
num_str = str(nums)
if num_str == num_str[::-1]:
pal += 1
else:
count = 0
num_el = num_str
while (count < 60):
np_total = int(num_el) + int(num_el [::-1])
count += 1
nums_el = str(np_total)
num_el = nums_el
if num_el == nums_el [::-1]:
nonlych += 1
count = 999 # breaks while loop
if (count != 999):
lychrel += 1
print(nums, "looks like a lychrel number")
nums += 1