gpt4 book ai didi

python - 如何在Python中使代码循环3次并在其周围有一个while循环

转载 作者:行者123 更新时间:2023-12-01 04:18:21 26 4
gpt4 key购买 nike

使用 python 非常有限并且完全卡住了,我设法在下面的代码上运行一个 while 循环,以便用户可以不断输入代码,直到输入正确的代码。

我现在想做的是添加一个 for 循环,这样它只要求用户输入代码(4 个错误的数字)3 次,然后将其锁定。同时,它需要一个 while 循环来确保如果用户输入的数字多于或少于 4 位,它会持续运行并且不会将其锁定。

我只是无法让 for 循环和 while 循环同时工作,并且不知道我做错了什么。

user = ("1234")

valid = False

while not valid:

#for i in range (3):

user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()

if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break

if user != ("1234") :
print ("that is incorrect, please try again")
valid = False



elif len(user) > 4:
print ("That is incorrect, please try again")
valid = False

elif len(user) < 4:
print ("That is incorrect, please try again")
valid = False
else:
print ("You have been locked out!! Alarm!!!!!!")

最佳答案

user = ("1234")

counter = 0

while counter < 3:

user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()

if len(user) != 4:
print("I said 4 digits!")
continue

if user == ("1234") :
print("You have cracked the code, well done")
break

print ("that is incorrect, please try again")
counter += 1

if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
else:
print ("Everything is fine.")

关于python - 如何在Python中使代码循环3次并在其周围有一个while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34046587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com