# Stuck in infinite loop while printing out wrong number

Hi y’all I’m working on a problem we have to design a program that takes as input a 9 digit number where no digit appears twice and produces as output an arrangement of the same 9 digits corresponding to the next highest number. So for example if the input is 781623954 the output would be 781624359.

My code below runs infinitely while displaying only a +1 number (for eg if I input 781623954 it will repeat 781623955 9 times then repeat 781623960 9 times). I’ve written my logic for each line below but can’t find where I went wrong. Can anyone let me know which part of my logic is wrong?

``````#User's input number, define variables
user_input= input("write a nine digit number without repeating any digit: ")
candidate= int(user_input)+1
found= True

#as long as each digit of candidate can be found in user input number...
while found:
#assign digit to each number in candidate as it
#goes through loop for each number in candidate
for digit in str(candidate):
#what has to happen in order for candidate to be false.
if digit not in user_input:
found = False    #Needs to be false so the loop keeps running?
#for loop keeps going for each number in user_input
else:
found= True    #Is this necessary?
print("The number is", candidate)
#Add one to try the next candidate
candidate=candidate+1
``````

I’ll be going through the script step by step:

There’s nothing here that checks if the user actually met the condition. Okay for trying out things, but may lead to unexpected issues when you don’t know what someone might enter.

This only checks if a digit of `candidate` is missing from `user_input`, but not the other way around, which you also need to make sure the digits are exactly the same. The easiest way to do that would be to compare sets of the digits.

No, this will actually end the outer `while` loop after its current run, which is probably not what you want, because that way no further candidates will be checked.

I’m not sure what you’re trying to do here, the `present` variable is never read, so this effectively doesn’t do anything.

This runs every time a digit in the `candidate` is present in the `user_input`, that’s why you get so many lines for each candidate.

The loop is missing a condition that ends it when a candidate that meets all conditions has been found. A common pattern how to do this would be to initialize a variable to `None`, check that it is still `None` in the loop condition, and assign it the result when there is one:

``````found = None
while found is None:
# check whatever conditions you need
if condition:
found = candidate
candidate += 1
``````

Ideally you should also check if there can’t be any more fitting number, for example if `candidate` got so large that it has more digits than the user input, and `break` the loop in that case.