An integer value has no zeros left; if you need to keep them you should keep their value as string, but if the intention is to do this to validate a month, don’t. Month 02 is the same as month 2, so validating if it has two characters is not a sufficient validation (42 is a valid month? It has two characters).
If you wish to validate whether a number has been entered and if it is a valid month you will need to treat the exception ValueError
which is launched by int
when the value is not numerical and to know if it is a valid value for the month just check if it is between 1 and 12 inclusive. Theoretically if I enter "month 2" or "month 02" should be the same thing, then it cannot validate if there are two characters.
while True:
try:
month = int(input('Mês: '))
if 1 <= month <= 12:
break
print('Informe um valor entre 1 e 12')
except ValueError:
print('Informe um valor numérico')
When executing you would have an exit like:
>>> Mês: a
Informe um valor numérico
>>> Mês: 13
>>> Informe um valor entre 1 e 12
Mês: 5
See working on Repl.it
Important note: One string with zero left is completely different from a value with zero left. In Python 2 the left zero on an integer was used to indicate that the value was octal, that is, base 8 and not base 10. Do, for example, print(010)
in Python 2 will display 8, as the number 010 in base 8 equals the number 8 in base 10. In Python 3 this notation has been changed to 0o10
, with the letter o
between values and started generating a syntax error for integers with 0 left. Be very careful not to confuse things.
It is that I wanted at the same time to ensure that it was not possible for the user to type another character, just to type numbers.
– Gabriel