Reputation: 63
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()
Upvotes: 1
Views: 60
Reputation: 76194
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]
Upvotes: 1