Home > OS >  How do I keep a loop going with a variable that changes in every loop
How do I keep a loop going with a variable that changes in every loop

Time:10-23

So I'm new to coding and I'm struggling with the following exercise So we start with a random number and we have to count the even numbers and the odd numbers. With this, we make a second number that starts with the amount of the even numbers, amount of the odd numbers, and the amount of numbers in total. We should continue this until the number 123 is reached. For example: number = 567421 --> odd numbers = 3 , even numbers = 3 , total numbers = 6 --> new number = 336 -->...

I had an idea to write it like this:

number = input()
evennumbers = ''
oddnumbers = ''
a = len(number)


while number != '123':
    for i in str(number):
        if int(i) % 2 == 0:
            evennumbers  = i
        else:
            oddnumbers  = i
    b = len(evennumbers)
    c = len(oddnumbers)
    number = input(print(f"{b}{c}{a}"))

But I have no idea how to keep this loop going with the variable 'number' until 123 is reached

CodePudding user response:

You need your variable initialization to be inside the while loop, and remove the input(print(... on the final line.

number = '567421'
while number != '123':
    print(number)
    evennumbers = ''
    oddnumbers = ''
    a = len(number)
    for i in str(number):
        if int(i) % 2 == 0:
            evennumbers  = i
        else:
            oddnumbers  = i
    b = len(evennumbers)
    c = len(oddnumbers)
    number = f"{b}{c}{a}"

You could simplify like this:

while number != '123':
    print(number)
    total = len(number)
    odds = sum(int(digit) % 2 for digit in number)
    evens = total - odds
    number = f"{evens}{odds}{total}"
    
  • Related