0

我试图让这段简单的代码运行,它迭代一个由四个随机数组成的序列,直到它与用户输入的四位数字相匹配。我知道有更简单的方法可以做到这一点,但我只是想知道为什么它不起作用。程序将编译,当它到达 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')
4

2 回答 2

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')
于 2013-02-15T22:02:17.077 回答
0

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

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

于 2013-02-15T21:33:41.330 回答