If you want to check if a string contains a number and then validate if that number is between certain values, you do not need to use isdigit
and then convert to int
. Of course if the user always type correct values, there will be no problems, the problem is that there are several characters for which isdigit
returns True
but error when converting to int
, see here.
All right it’s a corner case and "probably the user will never type these characters". But the best - and most guaranteed - would be to make the conversion with int(entrada)
and capture the ValueError
to know if a number has not been entered (more or less thus).
Anyway, in your case, just make a loop infinite and only interrupt it if all conditions are met:
tabuleiro = [ '' ] * 9
while True:
try:
casa = int(input('Escolha onde quer jogar: '))
if 0 <= casa <= 8: # valor válido
if tabuleiro[casa] == '':
break # valor válido, encerra o loop
else:
print(f'Casa {casa} está ocupada')
else:
print('Valor deve estar entre 0 e 8')
except ValueError:
print('Não foi digitado um número')
# usar tabuleiro[casa]...
I mean, I read the dice and I try to turn them into numbers with int
. If a number has not been typed, it launches the ValueError
and falls into the block except
.
If it is number, I check if it is in the correct value range and if the house is occupied (and in each case I print the respective message). If everything is OK, I close the loop with break
.
As the rest of the program was not posted, it was unclear whether the loop should be stopped or if something should be done with the casa
right there. If that’s the case, just do what you need with the position casa
within the if tabuleiro[casa] == ''
(instead of the break
, do what you need to do in the if
).
Of course you could even separate each check into a specific function, as suggested to another answer. But I think in this case neither compensates, the checks are too simple - not to mention that each function suggested there is calling int
again (i.e., he converts to int
twice, unnecessarily - apart from the problem of isdigit
already mentioned, which does not always guarantee that the conversion to int
will work).
Have some options here and here
– hkotsubo