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– Leo Lamas