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

Asked

Viewed 149 times

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: ")
  • Try to put an Else no while com exit()

1 answer

0


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

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

To solve the infinite loop problem, simply replace line 6 with:

while resp != "0":

Some considerations regarding your code:

  • Try to be homogeneous in spacing 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: https://www.python.org/dev/peps/pep-0008/.
  • On line 29 you do an unnecessary check. For the program to get there, it is guaranteed (see line 16) that a != ''.

Browser other questions tagged

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