Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}"
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading