1

I'm writting a code for rock scissor paper game. But when I run it, it falls into infinite loop.

The problem happened in following code. Why this code result in infinite loop for any input value? (my python version is 3.5.0)

class Peoples(object):            
    def recept(self):
        u = input('choose..r or s or p: ')
        print('choice: ',{'r':'rock','s':'scissor','p':'p'}.get(u,'{} (wrong input)'.format(u)))
        return {'s':0,'r':1,'p':2}.get(u,self.recept())

P=Peoples()
P.recept()

1 Answer 1

1

Because the second argument of get gets executed regardless of whether it will ultimately be used by get. You ought to break it up into multiple lines so it only recursively calls when necessary:

d = {'s':0,'r':1,'p':2}
if u in d:
    return d[u]
else:
    return self.recept()

But really, it would be preferable to not use recursion at all, since you'll hit the maximum recursion depth and crash after the user chooses an invalid input enough times in a row.

def recept(self):
    d = {'s':0,'r':1,'p':2}
    while True:
        u = input('choose..r or s or p: ')
        print('choice: ',{'r':'rock','s':'scissor','p':'p'}.get(u,'{} (wrong input)'.format(u)))
        if u in d:
            return d[u]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.