Error on line 12: You wrote while opcao == 1 or 2 or 3:
. On that line you’re not saying "If option is 1, 2 or 3, do.", you’re saying "If option is 1, do it. If not, if 2, do it. If not, if 3, do it.".
The operator or
will return True
if one of the conditions is true (True). In Python
, all numbers are treated as True
except the 0 which is treated as False
.
The first condition was perhaps not true, but the others would surely be because in the or 2 or 3
, the conditions are separate and the numbers 2 and 3 alone are True
. Soon the block while
would never end. To fix this you have 2 options:
Option 1:
while opcao == 1 or opcao == 2 or opcao == 3:
Option 2: ( Not yet for you because you would need to learn about list and operator "in" )
while opcao in [1,2,3]:
Now following its objective, the question of the option would always repeat itself because the while
repeats the code while a condition is true (True), that is, even if the option chosen by the user was the correct one (1,2,3), the code would repeat itself because the condition is opcao == 1 or opcao == 2 or opcao ==3
.
In order that the code is not repeated if the user puts the correct option, you must change the comparison signal ==
for !=
.
OTHER MISTAKES:
The else
does not work with while
. When you finish the block it goes straight to the line of the else
. If you want to use it, you will have to put one if
.
At the beginning of the code, you do not need to close the int
with parentheses, although this does not generate any problem. It is better you do int(input('Digite o total de eleitores: '))
The program will never leave the first repeat ( first while ), because the condition c < eleitores
will always be True
, since the variable c
cannot be changed as the condition of the second while
(where the variable is changed) will be False
.
CODE CORRECTED AND IMPROVED:
c = 0
opcao = 0
cand_a = 0
cand_b = 0
cand_c = 0
print('''CANDIDATOS:
PARA VOTAR NO CANDIDATO A DIGITE 1
PARA VOTAR NO CANDIDATO B DIGITE 2
PARA VOTAR NO CANDIDATO C DIGITE 3 ''')
while c < 3:
while opcao != 1 and opcao != 2 and opcao != 3::
c = c + 1
opcao = int(input(f'\nDigite a opção do {c} eleitor: '))
if opcao == 1:
cand_a = cand_a + 1
elif opcao == 2:
cand_b = cand_b + 1
elif opcao == 3:
cand_c = cand_c + 1
else:
print("A opção que você digitou é inválida.")
opcao = 0
print(f'\nO número de votos no candidato A foi de {cand_a} eleitores.')
print(f'O número de votos no candidato B foi de {cand_b} eleitores.')
print(f'O número de votos no candidato C foi de {cand_c} eleitores.')
Thank you very much!
– Mateus
No problem :)
– JeanExtreme002