Python辅助简单输入和随机数

时间:2013-02-15 21:25:24

标签: python random input python-3.x

我试图让这段简单的代码运行,它迭代一系列四个随机数,直到它与用户输入的四位数相匹配。我知道有更简单的方法可以做到这一点,但我只是想知道为什么它不起作用。程序将编译,当它到达while检查时,终端屏幕永远不会更新,程序也不会终止。感谢

import random
attempts = 0
pin = input("Please enter your four digit pin: ")
str_pin1 = str(pin)


while True:
    digit1 = random.randint(0,9)
    digit2 = random.randint(0,9)
    digit3 = random.randint(0,9)
    digit4 = random.randint(0,9)
        digit1 = str(digit1)
        digit2 = str(digit2)
        digit3 = str(digit3)
        digit4 = str(digit4)
    attempts = attempts +1

    if digit1 == str_pin[0] and digit2 == str_pin[1] and digit3 == str_pin[2] and   str_pin[3]:)
        break
print('it took', attempts, 'for random number to find your code')

2 个答案:

答案 0 :(得分:1)

你可以这样做:

import random
attempts = 0
pin = input("Please enter your four digit pin: ")
guess = ""

while guess != pin:
    guess = str(random.randint(0,10000))
    while len(guess) < 3:
        guess = "0" + guess
    attempts = attempts +1

print('it took', attempts, 'for random number to find your code')

答案 1 :(得分:0)

一个简单的错字:你digit2语句的第二和第三种情况都有if,所以除非pin在两个地方都有相同的数字,否则永远不会匹配。

此外,整数与字符串的比较永远不会相等。您需要将每个随机数字转换为字符串。