附加练习
1.我的代码有个bug,为什么门锁的密码要猜11次而不是10次?
A:因为在循环体外已经有过一次input-12行,如下:
11 code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) 12 guess = raw_input("[keypad]> ") 13 guesses = 0 14 15 while guess != code and guesses < 10: 16 print("BZZZZEDDD!") 17 guesses += 1 18 guess = raw_input("[keypad]> ")
所以如果仅需要用不输入10次的话,则需要更改判断条件,如下:
11 code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) 12 guess = raw_input("[keypad]> ") 13 guesses = 0 14 15 while guess != code and guesses < 9: 16 print("BZZZZEDDD!") 17 guesses += 1 18 guess = raw_input("[keypad]> ")