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)

22nd Apr 2022, 6:44 PM
Syrine Ayedi
Syrine Ayedi - avatar
3 Antworten
+ 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.)
22nd Apr 2022, 7:13 PM
#0009e7 [get]
#0009e7 [get] - avatar
+ 3
Syrine Ayedi , it would be very helpful if you could share the task description with us. thanks!
22nd Apr 2022, 7:08 PM
Lothar
Lothar - avatar
+ 2
get thank you so much for your response it really helped 😊
22nd Apr 2022, 8:23 PM
Syrine Ayedi
Syrine Ayedi - avatar