I made a very simple game in Python but it goes into an infinite loop, someone, could you please help me with that?

0
                       #jogo do adivinha#

resp = 1
i = 5
x = 0
print ("Tente adivinhar o Número que eu estou pensando.")
print ("Você só tem 5 chances e o número está entre 0 e 100.")
while resp != 0:

    print ("")
    try:
        a=raw_input("tentativa %d: " %i)
        a= int (a)
    except:
        a = ''
        print ("Digite um número inteiro válido.")

    if a!='':
        while a!=x and i<5:
            if a==x:
                break

            elif a<x:
                print ("o numero é mais alto(+)")
                print ("")

            elif a>x and a!='':
                print ("o numero é mais baixo(-)")
                print ("")

            if a!='':
                i=i+1

            try:
                a=raw_input("tentativa %d: " % i)
                a= int(a)
            except:
                a = ''
                print ("Digite um número inteiro válido.")
                print ("")

    if i==5 and a!=x:
        print ("")
        print ("suas chances acabaram você perdeu!!!")
        print ("o número era', x")
        print ("")

    else:
        print ("")
        print ("Você acertou. Parabens!!!", a)
        print ("")

    resp=raw_input("Para jogar denovo aperte 1 - para sair aperte 0: ")
    
asked by anonymous 06.06.2017 / 00:14

1 answer

0

The loop problem lies in the fact that you are using the raw_input function to assign the value to the variable resp and to be comparing this value with an integer.

If the user types 0 , the value that is stored in resp is "0" (a string containing the 0 character).

To solve the infinite loop problem, simply substitute line 6 for:

while resp != "0":

Some considerations regarding your code:

  • Try to be homogeneous in the spacings and follow a pattern. Try to use a = int(a) , instead of a= int (a) . Good practices are found in Python Enhancement Proposal (PEP). I suggest you read at least PEP 8: link .
  • On line 29 you do an unnecessary check. For the program to arrive there, it is guaranteed (see line 16) that a != '' .
06.06.2017 / 00:57