Python程序将代码分配给随机整数,并检查用户输入是否不起作用

2024-04-19 05:36:43 发布

您现在位置:Python中文网/ 问答频道 /正文

#test
import subprocess
import time
import random
programClass=[]
code=random.randint(100,1000)
print('This is your secret code! PLEASE WRITE THIS DOWN!')
print(code)
numRafflePeople=0

tester=1
while tester==1:
    code1=input('What is your name, phone number, and email?\n')
    print('code',code1)
    code=code
    if code==code1:
        print('Blah')
        time.sleep(5)
        tester=2
    else:
        print('fail')
        tester=1

这个程序生成一个随机数,然后检查输入的数字是否与随机数相同,但是当我运行程序时,程序似乎无法识别它们是否相同

随机数是303。我会键入303,失败信息会被打印出来,有人能解释一下我代码中的错误吗


Tags: testimport程序yourtimeiscoderandom
2条回答

当用户输入时,code1变成一个字符串。代码是整数

在布尔值中比较这两者时,code==code1,它将始终为false

把它改成:

code1=int(input('What is your name, phone number, and email?\n'))

必须将输入转换为int

import time
import random

code = random.randint(100,1000)
print('This is your secret code! PLEASE WRITE THIS DOWN!')
print(code)

tester = 1
while tester == 1:
    code1 = int(input('What is your name, phone number, and email?\n'))
    print('code', code1)
    if code == code1:
        print('Blah')
        time.sleep(5)
        tester = 2
    else:
        print('fail')
        tester = 1

相关问题 更多 >