Validate an integer number in Python 3

Asked

Viewed 77 times

1

I am studying the Python 3 language and I am following an online course, where the teacher passes the following challenge:
"Make a program that plays PAR or ODD with the computer. The game will be stopped when the player LOSES, showing the total consecutive wins he has won at the end of the game."
And although I’m not yet a programmer, I managed to develop the program. However, I decided to try to increment with a validation for the numbers that would be typed by the user, in case this type a string or a symbol, for example, the loop would return in a similar way as I did for the string option (from P to even and I to odd). I must point out that I do not want to limit the user as to the number to be entered, as I limited the randint.
I believe it is a really easy problem to solve for any programmer already started, but even in the resolution, the teacher does only a validation of the string and not the number.
Below, follow the code commented with triple quotes and also with wire, for a better understanding of my question:

from random import randint

cont = 0
while True:
    comp = randint(0, 99)
    palpite = str(input('PAR ou ÍMPAR [P/I]? ')).strip().upper()
    while palpite not in 'PI': # Esta validação deu OK.
        print('Opção inválida. Digite P ou I.')
        palpite = str(input('PAR ou ÍMPAR [P/I]? ')).strip().upper()
    num = int(input('Escolha um número: '))
    '''
    while palpite == str:   #! Não consegui resolver <<<<<<<<<<<<<<<<
        print('Opção inválida. Digite um número inteiro.')
        num = int(input('Escolha um número: '))
    '''
    res = (num + comp) % 2
    print(f'Eu escolhi {comp} e você escolheu {num}.')
    if res == 0 and palpite in 'P':
        cont += 1
        print(f'{num + comp} é PAR! Você GANHOU!')
    elif res != 0 and palpite in 'I':
        cont += 1
        print(f'{num + comp} é ÍMPAR! GANHOU!')
    elif res == 0 and palpite in 'I':
        print(f'{num + comp} é PAR! Você PERDEU!')
        print(f'Você ganhou {cont} vezes.')
        break
    elif res != 0 and palpite in 'P':
        print(f'{num + comp} ÍMPAR! Você PERDEU!')
        print(f'Você ganhou {cont} vezes.')
        break
print('>>>>> GAME OVER <<<<<')

Thanks for your attention and cooperation!

  • Try to use the function isnumeric(): https://www.w3schools.com/python/ref_string_isnumeric.asp

1 answer

1

Use:

try...except with using int() nestled:

while True:
  try:
    num = int(input('Escolha um número: '))
    break
  except ValueError:
    print("Não é um número!")

print(f'{num} é um número inteiro.')

Using the method str.isdecimal():

while True:
  inp = input('Escolha um número: ')
  if inp.isdecimal(): break
  print("Não é um número inteiro decimal!")

num = int(inp)

print(f'{num} é um número inteiro decimal.')

Do not use:

When you want to convert an input string to decimal integer don’t use the methods str.isdigit() or str.isnumeric().
At first it may seem a good idea to use these methods, but when we are talking about Unicode every care is needed.
No use filtering the input with the method str.isascii() before processing a string with str.isdigit() or str.isnumeric(), both methods are permissive for numerical elements housed in the Unicode block Latin 1 Supplement which cannot be converted, without special treatment, into decimal integers.

According to the documentation:

str.isdigit()
Returns True if all the characters in the string are digits and there is at least one character, False otherwise.
Digits include decimal characters and digits that need special treatment, such as over-written digit compatibility.
That includes digits that cannot be used to form numbers in base 10, such as the numbers of Kharosthi.
Formally, a digit is a character that has the property with value Numeric_Type=Digit or Numeric_Type=Decimal.

while True:
  inp = input('Escolha um número: ')
  if inp.isdigit(): break
  print("Não é um número inteiro decimal!")

num = int(inp)

print(f'{num} é um número inteiro decimal.')

Escolha um número: ²3455
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    num = int(inp)
ValueError: invalid literal for int() with base 10: '²3455'

str.isnumeric()
Returns True if all characters in the string are numeric characters, and there is at least one character, False otherwise.
Numeric characters include digits, and all characters that have the Unicode numeric value/property*, that is: U+2155, a fifth of ordinary fraction.
Formally, numeric characters are those that have properties with value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

while True:
  inp = input('Escolha um número: ')
  if inp.isnumeric(): break
  print("Não é um número inteiro decimal!")

num = int(inp)

print(f'{num} é um número inteiro decimal.')

Escolha um número: 
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    num = int(inp)
ValueError: invalid literal for int() with base 10: ''
  • 1

    Thanks a lot, Augusto! It helped me a lot! And I really didn’t want to use the conversion method. The answer was very clear. Thanks a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.