0
Does anyone know why my code will not read the x value if i give a number bigger or smaller than 4 digits?
I think the bug is when the second while loop is being executed but i can't really know what's wrong because the syntax is supposed correct . Here's the code : list=[] cpt=0 while cpt<10: Â Â x=int(input("Donner un entier:\n")) Â Â ch=str(x) Â Â while len(ch)!=4: Â Â Â Â x=int(input("Donner un entier:\n")) Â Â Â list.append(x) Â Â cpt+=1 Â Â print(list) dup=sorted(set(list)) print(dup)
3 Answers
+ 6
Yes, it is indeed a problem with the inner (second) loop.
In that loop, you assign a new value to `x`, but `ch` is never changed in it. So that it is an infinite loop because the condition=true is never changed.
There are at least two easy solutions:
1. Add the `ch=str(x)` line to the inner loop as well (after the `x=[âŠ]` line).
2. Do not use the `ch` variable and replace it with `str(x)` in the inner loop's condition. So that `str(x)` is evaluated before each iteration (and thus only dependent on `x`), but either way, you would still need to evaluate it at each iteration, storing the value to a variable or not. And the variable is not used at any other place (at least in the code bit you gave us), so they are roughly the same, with the latter one using one variable less and having less lines and characters in the source code. (I am not necessarily propagating the second answer, it is just to "open the eyes" and explain why it is a thing in case you just started programming and has been taught strict rules.)
+ 3
Syrine Ayedi ,
it would be very helpful if you could share the task description with us.
thanks!
+ 2
get thank you so much for your response it really helped đ