Why does loop in other loop woks wierd?

When i make loop in other loop it gives me duplicated value

a = []
i = 0
while True:
  i += 0.1
  i = round(i,1)
  a.append(i)
  if i == 13:
    break
  
maybe_corr_nums1 = []
maybe_corr_nums2 = []
for i in a:
  for j in a:
    num = i + j
    num = round(num,1)
    if num == 8:
      maybe_corr_nums1.append(i)
      maybe_corr_nums2.append(j)
print(maybe_corr_nums2)    

      
maybe_corr_nums3 = []
corr_nums1 = []
for i in a:
  for j in maybe_corr_nums1:
    num = i + j
    num = round(num)
    if num == 13:
      maybe_corr_nums3.append(i)
      corr_nums1.append(j)
print(maybe_corr_nums3)

First print gives me right result, but second gives me list with duplicated numbers

Upvotes: -1

Views: 49

Answers (1)

Bond 007
Bond 007

Reputation: 220

try this:

The error seems to be in num = round(num) of the second loop which explained why you had the repetition so I changed it to num = round(num,1) as it is supposed to do the same as above which seems to work but starts at 5 :(.
Is it supposed to start from 0 and go to 13?

a = []
i = 0
while True:
  i += 0.1
  i = round(i,1)
  a.append(i)
  if i == 13:
    break
  
maybe_corr_nums1 = []
maybe_corr_nums2 = []
for i in a:
  for j in a:
    num = i + j
    num = round(num,1)
    if num == 8:
      maybe_corr_nums1.append(i)
      maybe_corr_nums2.append(j)
print(maybe_corr_nums2)    

      
maybe_corr_nums3 = []
corr_nums1 = []
for i in a:
  for j in maybe_corr_nums1:
    num = i + j

    num = round(num,1) ## added ,1 like it is in the first one 
    if num == 13:
      maybe_corr_nums3.append(i)
      corr_nums1.append(j)

print(maybe_corr_nums3)

Upvotes: 2

Related Questions