- 帖子
- 1
- 精华
- 0
- 积分
- 12
- 阅读权限
- 10
- 注册时间
- 2016-3-29
- 最后登录
- 2016-5-9
|
- # 猜数字游戏
- import random
- def create_code():
- codenum = [1,2,3,4,5,6,7,8,9,0]
- code = ''
- i = random.randint(0,9)
- while True:
- if 4 == len(code):
- break
- if str(codenum[i]) in code:
- i = random.randint(0,9)
- else:
- code += str(codenum[i])
- return code
- def validate_code(code, guess_code):
- aNum = 0
- bNum = 0
- if len(code) != len(guess_code):
- print("请输入【4位数字】密码")
- return False
- # elif type(guess_code) != type(0):
- # print('请输入数字')
- # return False
- else:
- for i in range(len(code)):
- if code[i] == guess_code[i]:
- aNum += 1
- elif guess_code[i] in code:
- bNum += 1
- if aNum == 4 and bNum == 0:
- print("恭喜你,猜对了",end = '')
- print(aNum,'A',bNum,'B')
- return True
- else:
- print(aNum,'A',bNum,'B')
- return False
- def guess_game():
- code = create_code()
- print('让我们来猜一个4位数密码')
- while True:
- guesscode = input("请输入4位数字密码")
- if validate_code(code,guesscode) :
- break
- else:
- continue
- guess_game()
复制代码 看了test777的代码才知道random.sample(numbers,pwd_length)函数,惭愧。。
自学Python,不太久,加油 |
|