0

My code is this:

num1 = int(input(": "))
num2 = int(input(": "))
list1 = []
x, z, y = 0, 0, 0
while x < 100:
    z += num1
    y += num2
    list1.append(z)
    list1.append(y)
    x += 1
for i in list1:
    if list1.count(i) > 1:
        print(i)
        break

It works fine but i wanted to change

while x < 100:

because it is sloppy to this:

num1 = int(input(": "))
num2 = int(input(": "))
list1 = []
x, z, y = 0, 0, 0
for i in list1:
  while list1.count(i) < 2:
    z += num1
    y += num2
    list1.append(z)
    list1.append(y)
    x += 1
else:
    print(i)

and NameError: name 'i' is not defined occurs. I am e new member here and just started learning Python. Any help?Thanks in advance!

Krupskaya
  • 1
  • 1
  • With your current indentation `else` is part of your `for` loop, not your `while` loop. As list1 is empty variable i never gets assigned and thus raises the error you see when you try to print it. – ScootCork Jan 06 '21 at 16:34

2 Answers2

0

Common error. you just didn't indent the else. At least that solved the issue when I ran the code. else: print(i)

Saraverflow
  • 15
  • 1
  • 7
0

The reason for the 'i' undefined error is that you wrote the print(i) statement at the same level as the for loop. The i variable is only accessible to statements inside your for loop not outside it.

Also your code will not find the LCM because you made the mistake of calling a for loop on an empty list. If the list is empty the for loop won't even run once.

In order to streamline your code, I suggest doing away with lists entirely and using simple if-else statements and a while loop

Here's my approach -

num1 = int(input(": "))
num2 = int(input(": "))

greaterNum = None
LCM = None

if num1 > num2:
    greaterNum = num1
else:
    greaterNum = num2

while True:
    if((greaterNum%num1 == 0) and (greaterNum%num2 == 0)):
        LCM = greaterNum
        print(LCM)
        break
    else:
        greaterNum += 1
ADUCJ
  • 123
  • 2
  • 13