Skip to main content
 首页 » 编程设计

python之如何猜测用户输入的 4 位密码(我们不知道)

2025年05月04日12cmt

有人可以解释一下如何在 python 中执行此操作吗?这个想法是找出用户输入的 4 位数代码(例如:3968)。如何设计一种算法来找到这个? 这是我得到的……:

code=int(input("Enter 4 digit secret code:")) 
count=0000 
while(count!=code): 
    count=count+1 
print("Your code was",count) 

这完美地工作......除了代码以 0 开头......例如:0387 它打印“你的代码是 387”作为 0387

有什么快速解决方法?

请您参考如下方法:

print("Your code was %04i" % count) 

% 表示这里有一个变量。 04 表示将其零填充为四个字符。 i 表示它是一个整数。 Docs here.

替代版本,使用新的,更灵活.format() formatting :

print("Your code was {:04n}".format(count))