Python:如何让程序在用户输入时提示用户一定的固定次数?

标签 python python-3.x input passwords prompt

在程序中,用户必须输入密码,如果输入错误,程序将再提示他两次,如果两次错误,程序将过期。我该怎么做呢?这是我到目前为止的程序...

password=input("Enter password:")
while password != 'cat': 
    print ("password is wrong, try it again")
    password= input ("Enter your password:")

print ("Password correct be happy")

最佳答案

慈善程序员

for trial in range(3):
    print ("Attempt no.",trial, end=" ")
    passw = input('.  Enter password > ')
    if passw == 'cat' : break
else:
    passw = 'cat'

是的,简单的 for 循环也有一个 else 子句:"Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement." .

关于Python:如何让程序在用户输入时提示用户一定的固定次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27063289/

相关文章:

python - 根据现有列值从 pandas 数据框中随机选择行子集

python - Python 中的关键字到底是什么?

python - 计算按周分组的单个列上值的出现次数

python - 加载特定用户的登录逻辑

python - 拼凑文件系统路径不起作用

java - 在java游戏中获取用户输入

c++ - 检查 cin 结果 c++

python - 如何从一组图像中获取随机图像?

python - 如何在 Python PIL 中为绘制文本设置适当的线宽?

python-3.x - Python Tkinter GUI 与 PyQT 的内存节省