Reputation: 3
I'm doing a project that is a quiz filling the gaps and I'm having an error and I can not identify. After I fail to respond to a gap, the quiz does not show the phrase that should appear and an error appears. Can someone help me? I have tried some things and nothing happens, always when an attempt to hit is wrong it shows the error instead of showing the amount of attempts that the player still has or that he has lost. Follow the code: PS: The code is in PT_BR
# coding=utf-8
# Meu quiz
print ("Escolha o nível de dificuldade para o seu jogo. Digite F para fácil, M para médio, ou D para difícil.")
# Lista do total de tentativas já feitas
count_list = []
perguntas = [
"Digite a palavra que corresponde ao espaço 0: ",
"Digite a palavra que corresponde ao espaço 1: ",
"Digite a palavra que corresponde ao espaço 2: ",
"Digite a palavra que corresponde ao espaço 3: "
]
def verificacao(frase, gabarito, tentativas):
# Verificação das palavras do jogo com contabilização
print
print (frase)
print
index = 0
while len(count_list) < tentativas and index < (tentativas + 1):
pergunta = input(perguntas[index]).lower()
if index == tentativas and pergunta == gabarito[index]:
print
print ("Parabéns! Você ganhou!")
break
if pergunta == gabarito[index]:
print
print ("Você acertou!")
print
frase = frase.replace(str(index), gabarito[index])
print (frase)
index += 1
print
else:
count_list.append(1)
print
print ("Você errou. Você tem mais") + str(
tentativas - len(count_list)) + "tentativa(s)."
print
if len(count_list) == tentativas:
print ("Você perdeu.")
break
# Variáveis do jogo
frase_facil = "Água __0__, pedra __1__, tanto __2__ até que __3__."
frase_medio = "De __0__, poeta e __1__, todo __2__ tem um __3__."
frase_dificil = "Um __0__, de exemplos __1__ mais que uma __2__ de __3__."
frases = [frase_facil, frase_medio, frase_dificil]
gabarito_facil = ['mole', 'dura', 'bate', 'fura']
gabarito_medio = ['medico', 'louco', 'mundo', 'pouco']
gabarito_dificil = ['grama', 'vale', 'tonelada', 'conselhos']
gabaritos = [gabarito_facil, gabarito_medio, gabarito_dificil]
def attempts():
# Verifica se a tentativas informada é válida, e retorna apenas se o valor for válido
while True:
try:
tentativas = int(
input("Quantas tentativas que você quer ter? "))
return tentativas
break
except ValueError:
print("Você precisa digitar um número. Tente outra vez.")
continue
while True:
# Pega o input do usuário sobre o nível de dificuldade e número de tentativas desejada, para iniciar o quiz correto com a dificuldade correta.
nivel_dificuldade = input("Nível de dificuldade: ")
tentativas = attempts()
if nivel_dificuldade.lower() == "f" or nivel_dificuldade.lower(
) == "facil" or nivel_dificuldade.lower() == "fácil":
verificacao(frase_facil, gabarito_facil, tentativas)
break
elif nivel_dificuldade.lower() == "m" or nivel_dificuldade.lower(
) == "medio" or nivel_dificuldade.lower() == "médio":
verificacao(frase_medio, gabarito_medio, tentativas)
break
elif nivel_dificuldade.lower() == "d" or nivel_dificuldade.lower(
) == "dificil" or nivel_dificuldade.lower() == "difícil":
verificacao(frase_dificil, gabarito_dificil, tentativas)
break
print ("Para escolher a dificuldade do seu quiz, você precisa apertar F, M ou D. Tente novamente.")
Upvotes: 0
Views: 197
Reputation: 15652
The Problem
The problem is with line 46 of the code you've posted, in the else
block in the first while
loop. This part:
print ("Você errou. Você tem mais") + str(
tentativas - len(count_list)) + "tentativa(s)."
Since you close the parentheses around "Você errou. Você tem mais"
, you are printing just that string. Then you attempt to concatenate the result of print
with the next string (str(tentativas - len(count_list))
), so you get the error:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
since print
does not return anything (i.e. None
).
The Solution
To Fix this simply place that first closing parenthesis at the end of the line so that all string concatenation is done within the parentheses and the whole result is printed.
Here's what that looks like:
print ("Você errou. Você tem mais" + str(
tentativas - len(count_list)) + "tentativa(s).")
Upvotes: 1