Python帮助处理简单输入和随机数
我正在尝试运行一段简单的代码,这段代码会不断生成四个随机数字,直到它们和用户输入的四位数字匹配。我知道有更简单的方法可以做到这一点,但我只是想知道为什么这段代码不工作。程序可以编译,但当它到达检查的地方时,终端的屏幕就不会更新,程序也不会结束。谢谢。
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 个回答
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')
0
这是一个简单的打字错误:在你的 if
语句的第二和第三个条件里,你都用了 digit2
,所以除非 pin
在这两个地方的数字是一样的,不然它永远不会匹配。
另外,把一个整数和一个字符串进行比较是永远不会相等的。你需要把每个随机数字转换成字符串。