![](/img/trans.png)
[英]How do you get Python to ask the user for an input 'x' amount of times?
[英]Python: How do you get a programme to prompt the user a certian fixed amount of times for a user input?
在該程序中,用戶必須輸入密碼,如果輸入的密碼錯誤,該程序將再次提示他兩次,如果兩次輸入的密碼都不正確,則該程序將過期。 我該怎么做。 到目前為止,這是我的程序...
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
子句: “循環語句可能具有else子句;當循環通過用盡列表(帶有for)終止循環或當條件變為false(帶有while)時執行該語句,但不是當循環由break語句終止時。” 。
嘗試這個:
import sys
max_tries = 3; current_tries = 0
password=input("Enter password:")
while password != 'cat':
if current_tries > max_tries:
print "too many tries"
sys.exit(0)
print ("password is wrong, try it again")
password= input ("Enter your password:")
current_tries +=1
print ("Password correct be happy")
max_tries = 3
password = None
for i in range(max_tries):
password = input("Enter Password:")
if password == "cat": break
if password != "cat":
print ("ERROR TOO MANY TRIES!")
else:
print ("You Win!")
是一種簡單的方法...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.